atcoder#ABC291H. [ABC291Ex] Balanced Tree

[ABC291Ex] Balanced Tree

Score : 600600 points

Problem Statement

You are given a tree TT with NN vertices. The ii-th edge connects vertices AiA_i and BiB_i.

Construct an NN-vertex rooted tree RR that satisfies the following conditions.

  • For all integer pairs (x,y)(x,y) such that 1x<yN1 \leq x < y \leq N,- if the lowest common ancestor in RR of vertices xx and yy is vertex zz, then vertex zz in TT is on the simple path between vertices xx and yy.
  • if the lowest common ancestor in RR of vertices xx and yy is vertex zz, then vertex zz in TT is on the simple path between vertices xx and yy.
  • In RR, for all vertices vv except for the root, the number of vertices of the subtree rooted at vv, multiplied by 22, does not exceed the number of vertices of the subtree rooted at the parent of vv.

We can prove that such a rooted tree always exists.

Constraints

  • 1N1051 \leq N \leq 10^5
  • 1Ai,BiN1\leq A_i,B_i \leq N
  • All values in the input are integers.
  • The given graph is a tree.

Input

The input is given from Standard Input in the following format:

NN

A1A_1 B1B_1

\vdots

AN1A_{N-1} BN1B_{N-1}

Output

Let RR be a rooted tree that satisfies the conditions in the Problem Statement. Suppose that the parent of vertex ii in RR is vertex pip_i. (If ii is the root, let pi=1p_i=-1.) Print NN integers p1,,pNp_1,\ldots,p_N, with spaces in between.

4
1 2
2 3
3 4
2 -1 4 2

For example, the lowest common ancestor in RR of vertices 11 and 33 is vertex 22; in TT, vertex 22 is on the simple path between vertices 11 and 33. Also, for example, in RR, the subtree rooted at vertex 44 has two vertices, and the number multiplied by two does not exceed the number of vertices of the subtree rooted at vertex 22, which has 44 vertices.

Figure

5
1 2
1 3
1 4
1 5
-1 1 1 1 1