#P5773. Dynamic Heavy-Light Path Decomposition on a Binary Tree

    ID: 19001 Type: Default 1000ms 256MiB

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 O(logN)O(\log N) different heavy paths.

For the purpose of this problem, you are given a rooted binary tree with NN nodes (numbered 11 through NN). The heavy-light decomposition is defined as follows. For any node uu, let size(u)\text{size}(u) be the number of nodes in the subtree rooted at uu. Among the children of uu, the child with the maximum size\text{size} is connected by a heavy edge and the other child (if any) is connected by a light edge. In the case where uu has two children with equal size\text{size}, if such a tie occurs after a deletion operation, you must retain uu’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 QQ 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 uu in the tree that currently has a heavy edge from it to one of its children vv, you should sum up vv over all such nodes uu.

inputFormat

The first line contains two integers NN and QQ (1N,Q1051 \le N, Q \le 10^5) representing the number of nodes in the tree and the number of deletion operations.

The next NN lines each contain two integers; the ii-th line contains LiL_i and RiR_i representing the left and right child of node ii 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 QQ 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 QQ 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 uu with a heavy edge to vv, sum up vv).

sample

5 3
2 3
4 5
0 0
0 0
0 0
4
5
3
7

2 2

</p>