A XOR tree

2.9

7 votes
Dynamic Programming, XOR, Implementation, Tree, Trees, Combinatorics, Data Structures, Lowest Common Ancestor, Mathematics
Problem

You are given a tree G with N nodes. The ith node of the tree has been assigned value Ai. We define d(u,v) as the bitwise xor of weight of nodes present on the simple path between u and v. You are required to find:
Ni=1Nj=i+1d(i,j)

Input format

  • The first line contains a single integer T denoting the number of test cases.
  • The first line of each test case contains an integer N that denotes the number of nodes in tree G.
  • The second line of each test case contains N space-separated integers denoting the initial weight on the nodes of the tree(Ai).
  • For each test case, (N1) lines follow. Each of these lines contains two space-separated integers u and v denoting that there is an edge between these two nodes.

Output format

For each test case(in a separate line), output the sum Ni=1Nj=i+1d(i,j), where d(i,j) is the bitwise xor of weight of nodes present on the simple path between i and j.

Constraints

1T10001N1051Ai109Sum of N over all test cases does not exceed 106

Time Limit: 4
Memory Limit: 256
Source Limit:
Explanation

In the first test case, we have A1=1,A2=3,A3=4. The tree looks as follows:

                                                                             

We have d(1,2)=A1A2=2, d(1,3)=A1A3=5, d(2,3)=A2A1A3=6. The sum is d(1,2)+d(1,3)+d(2,3)=2+5+6=13 and we output it.

In the second test case, there is only one edge and we find d(1,2)=A1A2=2 and output it.

Editor Image

?