#P11195. Tree Weight Modification
Tree Weight Modification
Tree Weight Modification
We are given a rooted tree with N nodes (numbered 1 through N) with node 1 as the root. Each node i has an integer weight a_i. An operation on the tree is defined as follows:
- Initialize u as the root.
- While u is not a leaf:
- Among all children of u, let v be a child with the maximum weight. (If there are several, one is chosen uniformly at random.)
- Update: set a_u \leftarrow a_v and a_v \leftarrow 0.
- If v is a leaf, remove v from the tree and stop; otherwise, set u \leftarrow v and repeat from step 1.
For any node v, define f(v) as the minimum number of nodes whose weights must be modified (each can be changed to any integer in the interval \([0, 2\times10^9]\)) so that, under any outcome of the tie‐breaking, the number of operations required to have the original weight of node v reach the root is as small as possible. It can be shown that under the fixed tree structure the best possible (or lower bound) number of operations is equal to the length of the unique path from the root to v.
In order for the process to follow this optimal route, the following must hold: For every node u on the path from the root to v (except for v itself), if u' is the next node on the path (i.e. the designated child), then for every other child w of u we must have
[ a_{u'} > a_w ]
The goal is to choose a set of nodes for which we modify the weights (and choose the new values arbitrarily) so that the condition above holds for every node on the root-to-v path and the total number of modifications is minimized.
You are given Q queries. For each query, given a node v, output f(v).
inputFormat
The input begins with a line containing two integers N and Q: the number of nodes and the number of queries.
The second line contains N integers: a1, a2, ..., aN, representing the weight of each node.
The third line contains N-1 integers: p2, p3, ..., pN, where pi is the parent of node i. (It is guaranteed that the tree rooted at node 1 is given.)
Each of the next Q lines contains a single integer v, indicating a query.
outputFormat
For each query, output an integer representing f(v) on a separate line.
Explanation of f(v): Let the unique path from the root to v be 1 = u0, u1, \ldots, ud = v. For every edge (ui, ui+1) (with 0 \le i < d), we require that the designated child (ui+1) has a weight greater than every other child of ui. In other words, for each such ui, if there exists any other child w (w \neq ui+1) with a_w ≥ a_{u_{i+1}} under the current weights, then a modification is needed (and one may instead choose to modify a_{u_{i+1}}). Thus, for each edge, the minimum number of modifications required is min( (# of offending siblings), 1 )
. Summing over the edges on the path gives f(v).
sample
5 3
5 3 4 2 1
1 1 2 2
3
4
5
0
1
2
</p>