CF BUDDY
← Problems·

1882D · Tree XOR

1900 · bitmasks, dfs and similar, dp

Problem: You are given a tree with nn vertices labeled from 11 to nn. An integer aia_{i} is written on vertex ii for i=1,2,,ni = 1, 2, \ldots, n. You want to make all aia_{i} equal by performing some (possibly, zero) spells.

Suppose you root the tree at some vertex. On each spell, you can select any vertex vv and any non-negative integer cc. Then for all vertices ii in the subtree^{\dagger} of vv, replace aia_{i} with aica_{i} \oplus c. The cost of this spell is scs \cdot c, where ss is the number of vertices in the subtree. Here \oplus denotes the bitwise XOR operation.

Let mrm_r be the minimum possible total cost required to make all aia_i equal, if vertex rr is chosen as the root of the tree. Find m1,m2,,mnm_{1}, m_{2}, \ldots, m_{n}.

^{\dagger} Suppose vertex rr is chosen as the root of the tree. Then vertex ii belongs to the subtree of vv if the simple path from ii to rr contains vv.

Input Format: Each test contains multiple test cases. The first line contains the number of test cases tt (1t1041 \le t \le 10^{4}). The description of the test cases follows.

The first line of each test case contains a single integer nn (1n21051 \le n \le 2 \cdot 10^{5}).

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

Each of the next n1n-1 lines contains two integers uu and vv (1u,vn1 \le u, v \le n), denoting that there is an edge connecting two vertices uu and vv.

It is guaranteed that the given edges form a tree.

It is guaranteed that the sum of nn over all test cases does not exceed 21052 \cdot 10^{5}.

Output Format: For each test case, print m1,m2,,mnm_1, m_2, \ldots, m_n on a new line.

Note: In the first test case, to find m1m_1 we root the tree at vertex 11.

  1. In the first spell, choose v=2v=2 and c=1c=1. After performing the spell, aa will become [3,3,0,1][3, 3, 0, 1]. The cost of this spell is 33.
  2. In the second spell, choose v=3v=3 and c=3c=3. After performing the spell, aa will become [3,3,3,1][3, 3, 3, 1]. The cost of this spell is 33.
  3. In the third spell, choose v=4v=4 and c=2c=2. After performing the spell, aa will become [3,3,3,3][3, 3, 3, 3]. The cost of this spell is 22.

Now all the values in array aa are equal, and the total cost is 3+3+2=83 + 3 + 2 = 8.

The values m2m_2, m3m_3, m4m_4 can be found analogously.

In the second test case, the goal is already achieved because there is only one vertex.

Sample Cases

Case 1

Input

2
4
3 2 1 0
1 2
2 3
2 4
1
100

Output

8 6 12 10 
0

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback