#P10560. [ICPC2024 Xi'an I] Holes and Balls

[ICPC2024 Xi'an I] Holes and Balls

题目描述

You are given nn balls, the ii -th ball's value is pip_i. It's guaranteed that p1,p2,,pnp_1,p_2,\dots,p_n is a permutation of 1,2,3,n1,2,3\dots,n.

There is also a rooted tree of nn vertices, each of the vertices is a hole, and each hole can only hold one ball.

The tree's root is the first vertex.

Now you need to fill the holes with the balls.

You need to throw each ball in order of 11 to nn in the following steps:

  1. Throw the ball into vertex 11.
  2. Let the vertex where the ball is be pp.
  3. If the pp -th vertex has already been filled with other balls, you need to choose a vertex xx and throw the ball into the xx -th vertex, then return to step 22. You need to guarantee that the xx -th vertex is the pp -th vertex's son and at least one vertex in the subtree of the xx -th vertex is not filled.
  4. Otherwise, the ball will fill the pp -th vertex.

After throwing all the balls, let aia_i express the value of the ball in the ii -th vertex.

You need to find the minimum lexicographical order of {an}\{a_n\}.

We define depidep_i as the number of vertices on the path from the ii -th vertex to the tree's root(the first vertex).

Specially, for any two vertices x<yx<y, it's guaranteed that depxdepydep_x\le dep_y.

输入格式

The first line contains a single integer n(1n5×105)n(1\le n\le 5\times 10^5) - the number of vertices in this tree.

The next line contains nn numbers, the ii -th number is pi(1pin)p_i(1\le p_i\le n). It's guaranteed that p1,p2,,pnp_1,p_2,\dots,p_n is a permutation of 1,2,3,n1,2,3\dots,n.

The next n1n-1 lines contain a description of the tree's edges. The ii -th of these lines contains two integers uiu_i and vi(1ui,vin)v_i(1\le u_i,v_i\le n) - the numbers of vertices connected by the ii -th edge.

It is guaranteed that the given edges form a tree.

And for any vertices x<yx<y, it's guaranteed that depxdepydep_x\le dep_y.

输出格式

Output nn integers, the minimum lexicographical order of {an}\{a_n\}.

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

3 1 5 4 2
9
9 2 6 3 5 7 1 4 8
1 2
1 3
2 4
2 5
3 6
3 7
4 8
4 9

9 2 1 3 6 4 8 5 7