#P5803. [SEERC 2019] Tree Permutations
[SEERC 2019] Tree Permutations
Description
One day, Mr. Cool built a tree with vertices (a connected undirected graph with no cycles). For each vertex , he specified two values: , which represents the parent of vertex , and , which represents the weight of the edge between and . Vertex is the root of the tree, so it has no parent.
You want to know what the tree Mr. Cool built looks like, but Mr. Cool refuses to tell you. However, he gave you some hints:
He wrote all the values and into a single list, obtaining an array of length .
$$b=[p_2, w_2, p_3, w_3, \dots, p_{n-1}, w_{n-1}, p_n, w_n]$$Then he randomly shuffled it, obtaining an array , and told you .
However, knowing only the array is not enough to restore the tree, so you decide to solve a harder problem.
A tree is called -long if and only if the path from vertex to vertex contains exactly edges.
A tree is called -perfect if and only if it is -long, and among all -long trees, the sum of edge weights on the path from vertex to vertex is the maximum possible.
Your task is to compute, for each , the sum of edge weights on the path from vertex to vertex in a -perfect tree. If no -perfect tree exists for some , output at that position.
Input Format
The first line contains an integer , representing the number of vertices in the tree.
The second line contains integers , representing the elements of array .
Output Format
Output one line with space-separated integers , where is the sum of edge weights on the path from vertex to vertex in a -perfect tree. If no -long tree exists, then .
3
1 1 2 2
2 3
3
2 2 2 2
-1 -1
6
1 4 5 4 4 4 3 4 4 2
-1 -1 -1 17 20
Hint
In the first sample, the -perfect tree is formed by the list (i.e., ), and the -perfect tree is formed by the list (i.e., ). The figures of these two trees are shown below (the edges on the path from vertex to vertex are drawn in bold).

In the second sample, there is no -perfect tree that can be constructed by rearranging .
In the third sample, only the -perfect and -perfect trees can be constructed. They are formed by the lists and , respectively. The figures of these two trees are shown below.

Translated by ChatGPT 5
京公网安备 11011102002149号