Under construction

Still being built. Things may change

Two Trees

Time limit5sMemory limit1024 MB

Summary
For each vertex i, find the maximum a_k over vertices k that lie in the subtree of i in both trees.
Level

Medium7 of 10

Topics
Tree, DFS, Segment tree
Solved
No attempts yet

Problem

Two trees T1T_1, T2T_2 and a sequence a1,a2,⋯ ,aNa_1, a_2, \cdots, a_N are given. Each tree has NN vertices, and the vertices are numbered from 1 to NN with no repeats. The root of both trees is vertex 1.

In T1T_1 and T2T_2, let PiP_i and QiQ_i be the sets of vertex numbers in the subtree rooted at vertex ii, respectively. Define mi=max⁡{ak∣k∈Pi∩Qi}m_i = \max\{a_k \mid k \in P_i \cap Q_i\}.

Write a program that computes m1,m2,⋯ ,mNm_1, m_2, \cdots, m_N.

Input

The first line contains NN. (1≤N≤250 000)(1 \leq N \leq 250\,000)

The second line contains the integers a1,a2,⋯ ,aNa_1, a_2, \cdots, a_N, separated by spaces. (1≤ai≤109)(1 \leq a_i \leq 10^9)

The next N−1N-1 lines each contain two integers uu and vv, separated by a space, that are the endpoints of an edge of T1T_1. (1≤u,v≤N; u≠v)(1 \leq u, v \leq N;\ u \neq v)

The next N−1N-1 lines each contain two integers uu and vv, separated by a space, that are the endpoints of an edge of T2T_2. (1≤u,v≤N; u≠v)(1 \leq u, v \leq N;\ u \neq v)

It is guaranteed that T1T_1 and T2T_2 are trees.

Output

Print m1,m2,⋯ ,mNm_1, m_2, \cdots, m_N, one per line, in order.

Examples1

  1. Example 1

    Input
    6
    7 10 5 14 8 100
    4 5
    1 5
    5 6
    1 2
    3 6
    1 4
    2 4
    1 5
    3 6
    4 6
    
    Expected output
    100
    10
    5
    14
    8
    100