Values in a Rooted Tree
Limits: 3 sec., 512 MiB
We have a rooted tree with nn vertices. The vertices are numbered 11 through nn, and the root is vertex 11. The ii-th edge connects vertices uiui and vivi. Vertex vv has an integer avav written on it.
For each vertex vv, find the maximum mm such that there exists xx, such that all values x,x+1,…,x+m−1x,x+1,…,x+m−1 are present on the path between the root and vertex vv.
Input
The first line contains an integer nn – the number of vertices in the tree.
The second line contains nn integers avav written on the vertices of the tree.
The following n−1n−1 lines contain two integers ui,viui,vi each – the ends of the ii-th edge.
Output
In a single line, print nn integers – the maximum mm for each 1≤v≤n1≤v≤n.
Constraints
1≤n≤3⋅1051≤n≤3⋅105,
0≤av≤1090≤av≤109,
1≤ui,vi≤n1≤ui,vi≤n.
Samples
Input (stdin) | Output (stdout) |
---|---|
5 2 4 0 3 5 1 2 1 3 2 4 2 5 | 1 1 1 3 2 |
Input (stdin) | Output (stdout) |
---|---|
7 1 3 2 2 0 11 10 4 5 5 1 2 5 2 3 1 6 7 6 | 1 2 4 3 2 1 2 |
Notes
In the first example, the answers for all vertices are the following.
Vertex 11. Since the root is vertex 11, thus the path between the root and vertex 11 contains the only vertex. In this case, m=1m=1.
Vertex 22. The path between the root and the vertex 22 contains two vertices 11 and 22 with values 22 and 44, respectively. Again, m=1m=1.
Vertex 33. The path between the root and the vertex 33 contains two vertices 11 and 33 with values 22 and 00, respectively. For vertex 33, the answer is m=1m=1.
Vertex 44. The path between the root and the vertex 44 contains three vertices 11, 22 and 44 with values 22, 44 and 33 respectively. Here the answer is m=3m=3, because for x=2x=2, the values x=2x=2, x+1=3x+1=3 and x+2=4x+2=4 are present on the path.
Vertex 55. The path between the root and the vertex 55 contains three vertices 11, 22 and 55 with values 22, 44 and 55 respectively. Here, the answer is m=2m=2 because, for x=4x=4, the values x=4x=4 and x+1=5x+1=5 are present on the path.