#P5773. Dynamic Heavy-Light Path Decomposition on a Binary Tree
Dynamic Heavy-Light Path Decomposition on a Binary Tree
Dynamic Heavy-Light Path Decomposition on a Binary Tree
JYY has recently been studying an advanced technique for processing tree structures called Heavy-Light Decomposition. In this method the edges of a tree are classified as either heavy or light. Consecutive heavy edges form paths along the tree, and it can be shown that on any path from a node to the root there are at most different heavy paths.
For the purpose of this problem, you are given a rooted binary tree with nodes (numbered through ). The heavy-light decomposition is defined as follows. For any node , let be the number of nodes in the subtree rooted at . Among the children of , the child with the maximum is connected by a heavy edge and the other child (if any) is connected by a light edge. In the case where has two children with equal , if such a tie occurs after a deletion operation, you must retain ’s heavy edge assignment from before the deletion; for the initial tree, when a tie occurs choose the left child as the heavy edge.
JYY will perform deletion operations. In each operation a leaf of the current tree is removed (it is guaranteed that the deleted node is indeed a leaf). After each deletion, you are to dynamically maintain the heavy-light decomposition (as described above) on the remaining tree and output the sum of the node numbers to which all heavy edges point. That is, for every node in the tree that currently has a heavy edge from it to one of its children , you should sum up over all such nodes .
inputFormat
The first line contains two integers and () representing the number of nodes in the tree and the number of deletion operations.
The next lines each contain two integers; the -th line contains and representing the left and right child of node respectively. A value of 0 indicates a missing (null) child. It is guaranteed that the given structure forms a rooted binary tree with root 1.
Each of the next lines contains a single integer representing the label of the leaf node to be deleted in that operation. It is guaranteed that the deletion order is valid.
outputFormat
Output lines. For each deletion operation, output the sum of the node numbers which are the endpoints of heavy edges in the current tree (i.e. for every node with a heavy edge to , sum up ).
sample
5 3
2 3
4 5
0 0
0 0
0 0
4
5
3
7
2
2
</p>