#P5803. [SEERC 2019] Tree Permutations

[SEERC 2019] Tree Permutations

Description

One day, Mr. Cool built a tree with nn vertices (a connected undirected graph with no cycles). For each vertex i>1i > 1, he specified two values: pi<ip_i < i, which represents the parent of vertex ii, and wiw_i, which represents the weight of the edge between ii and pip_i. Vertex 11 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 pip_i and wiw_i into a single list, obtaining an array bb of length 2n22 \cdot n - 2.

$$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 aa, and told you aa.

However, knowing only the array aa is not enough to restore the tree, so you decide to solve a harder problem.

A tree is called kk-long if and only if the path from vertex 11 to vertex nn contains exactly kk edges.

A tree is called kk-perfect if and only if it is kk-long, and among all kk-long trees, the sum of edge weights on the path from vertex 11 to vertex nn is the maximum possible.

Your task is to compute, for each kk, the sum of edge weights on the path from vertex 11 to vertex nn in a kk-perfect tree. If no kk-perfect tree exists for some kk, output 1-1 at that position.

Input Format

The first line contains an integer n (2n105)n \ (2 \leq n \leq 10^5), representing the number of vertices in the tree.

The second line contains 2n22 \cdot n -2 integers a1,a2,,a2n2 (1ain1)a_1, a_2, \dots, a_{2n-2} \ (1 \leq a_i \leq n-1), representing the elements of array aa.

Output Format

Output one line with n1n-1 space-separated integers w1,w2,w3,,wn1w_1, w_2, w_3, \dots, w_{n-1}, where wkw_k is the sum of edge weights on the path from vertex 11 to vertex nn in a kk-perfect tree. If no ii-long tree exists, then wi=1w_i=-1.

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 11-perfect tree is formed by the list [1,2,1,2][1, 2, 1, 2] (i.e., p2=1,w2=2,p3=1,w3=2p_2=1, w_2=2, p_3=1, w_3=2), and the 22-perfect tree is formed by the list [1,2,2,1][1, 2, 2, 1] (i.e., p2=1,w2=2,p3=2,w3=1p_2=1, w_2=2, p_3=2, w_3=1). The figures of these two trees are shown below (the edges on the path from vertex 11 to vertex nn are drawn in bold).

Sample 1

In the second sample, there is no kk-perfect tree that can be constructed by rearranging aa.

In the third sample, only the 44-perfect and 55-perfect trees can be constructed. They are formed by the lists [1,4,2,4,3,4,4,4,4,5][1, 4, 2, 4, 3, 4, 4, 4, 4, 5] and [1,4,2,4,3,4,4,4,5,4][1, 4,2, 4, 3, 4, 4, 4, 5, 4], respectively. The figures of these two trees are shown below.

Sample 3

Translated by ChatGPT 5