#P5773. [JSOI2016] 轻重路径

    ID: 4740 远端评测题 3000ms 500MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>2016各省省选江苏树链剖分,树剖

[JSOI2016] 轻重路径

Description

JYY has recently learned an advanced technique for processing tree structures, called “heavy-light decomposition”. This technique divides the edges of a tree into light edges and heavy edges. Connected heavy edges form several vertex-disjoint paths on the tree. With heavy-light decomposition, starting from any node and walking to the root, you will pass through at most (logN)(\log N) different heavy paths.

If you are not familiar with heavy-light decomposition, JYY gives a brief introduction here. For any node uu in a rooted tree, let size(u)size(u) denote the number of nodes in the subtree rooted at uu. Among all children of uu, choose the child vv with the largest sizesize value, and mark the edge (u,v)(u,v) as a heavy edge. All edges between uu and its other children are marked as light edges.

To simplify the problem, JYY only considers a rooted binary tree with NN nodes. The NN nodes are numbered from 11 to NN. If a node uu has two children with the same sizesize value, then by default the edge between uu and its left child is the heavy edge.

Now JYY wants to perform an additional QQ node-deletion operations. Each time, JYY will randomly delete a current leaf node of the binary tree, and you need to dynamically maintain the heavy-light decomposition of this tree.

For convenient output, after each operation you only need to output the sum of the indices of all nodes pointed to by heavy edges.

If after deleting a node, there exists a node uu whose two children have the same sizesize value, then we keep the heavy-edge choice of uu the same as it was before this operation was performed.

Input Format

The first line contains an integer NN.

The next NN lines: the ii-th line contains two integers Li,RiL_i, R_i, representing the index of the left child and the right child of node ii. Li=0L_i = 0 means node ii has no left child, and Ri=0R_i = 0 means node ii has no right child.

The (N+2)(N+2)-th line contains an integer QQ, indicating the number of deletion operations performed by JYY.

The (N+3)(N+3)-th line contains QQ space-separated positive integers, representing the indices of the leaves deleted by JYY.

The input guarantees that each deletion operation deletes a leaf.

Output Format

Output Q+1Q + 1 lines. Each line contains one integer: the sum of the indices of all nodes pointed to by heavy edges in the heavy-light decomposition. The first line corresponds to the initial decomposition, and the following QQ lines correspond to the decomposition after each deletion operation.

8
2 3
4 5
0 0
6 7
0 8
0 0
0 0
0 0
7
6 7 8 5 4 2 3

20
21
15
7
6
2
3
0

Hint

For 30%30\% of the testdata, N1000N \le 1000.

For 50%50\% of the testdata, N5×104N \le 5 \times 10^4.

For all testdata, N2×105N \le 2 \times 10^5.

Translated by ChatGPT 5