Under construction

Still being built. Things may change

Tree and XOR

Interview

Time limit3sMemory limit1024 MB

Summary
For each root r, find the minimum cost to make all vertex values equal, where XOR-ing a subtree by c costs its size times c.
Level

Medium6 of 10

Topics
Tree, DFS, Dynamic programming
Solved
No attempts yet

Problem

A tree with nn vertices is given. Each vertex is numbered from 11 to nn, and vertex ii has an integer aia_i written on it. You may perform as many operations as you want to make every aia_i equal.

In one operation, you choose a vertex vv and a non-negative integer cc. Then, for every vertex ii in the subtree rooted at vv, you replace aia_i with ai⊕ca_i \oplus c. Let ss be the size of the subtree rooted at vv. The cost of this operation is s⋅cs \cdot c. Here ⊕\oplus denotes bitwise XOR.

Let mrm_r be the minimum total cost needed to reach the goal when vertex rr is the root of the tree. Find m1,m2,…,mnm_1, m_2, \ldots, m_n.

Input

Each input contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041 \le t \le 10^{4}). Each test case follows.

The first line of each test case contains an integer nn (1≤n≤2⋅1051 \le n \le 2 \cdot 10^{5}).

The second line contains nn integers a1,a2,…,ana_1, a_2, \ldots, a_n (0≤ai<2200 \le a_i < 2^{20}).

Each of the next n−1n-1 lines contains two integers uu and vv separated by a space (1≤u,v≤n1 \le u, v \le n), denoting an edge between vertices uu and vv.

The given edges are guaranteed to form a tree.

The sum of nn over all test cases does not exceed 2⋅1052 \cdot 10^{5}.

Output

For each test case, print nn integers m1,m2,…,mnm_1, m_2, \ldots, m_n separated by spaces.

Hint

In the first test case, the goal can be reached in the following way.

  1. In the first operation, choose v=2v=2 and c=1c=1. After the operation, a=[3,3,0,1]a=[3, 3, 0, 1]. The cost of this operation is 33.
  2. In the second operation, choose v=3v=3 and c=3c=3. After the operation, a=[3,3,3,1]a=[3, 3, 3, 1]. The cost of this operation is 33.
  3. In the third operation, choose v=4v=4 and c=2c=2. After the operation, a=[3,3,3,3]a=[3, 3, 3, 3]. The cost of this operation is 22.

The total cost of this process is 3+3+2=83+3+2=8. It can be proven that no way reaches the goal with a cost below 88.

m2m_2, m3m_3, and m4m_4 can be found in the same way.

In the second test case, the tree has one vertex, so the goal is already met.

Examples1

  1. Example 1

    Input
    2
    4
    3 2 1 0
    1 2
    2 3
    2 4
    1
    100
    
    Expected output
    8 6 12 10 
    0