Tree and XOR
InterviewTime limit3sMemory limit1024 MB
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 vertices is given. Each vertex is numbered from to , and vertex has an integer written on it. You may perform as many operations as you want to make every equal.
In one operation, you choose a vertex and a non-negative integer . Then, for every vertex in the subtree rooted at , you replace with . Let be the size of the subtree rooted at . The cost of this operation is . Here denotes bitwise XOR.
Let be the minimum total cost needed to reach the goal when vertex is the root of the tree. Find .
Input
Each input contains multiple test cases. The first line contains the number of test cases (). Each test case follows.
The first line of each test case contains an integer ().
The second line contains integers ().
Each of the next lines contains two integers and separated by a space (), denoting an edge between vertices and .
The given edges are guaranteed to form a tree.
The sum of over all test cases does not exceed .
Output
For each test case, print integers separated by spaces.
Hint
In the first test case, the goal can be reached in the following way.
- In the first operation, choose and . After the operation, . The cost of this operation is .
- In the second operation, choose and . After the operation, . The cost of this operation is .
- In the third operation, choose and . After the operation, . The cost of this operation is .
The total cost of this process is . It can be proven that no way reaches the goal with a cost below .
, , and can be found in the same way.
In the second test case, the tree has one vertex, so the goal is already met.