Operations on a tree

4.2

6 votes
Algorithms, Basics of Greedy Algorithms, C++, Greedy Algorithms
Problem

You are given an undirected tree G with N nodes. You are also given an array A of N integer elements where A[i] represents the value assigned to node i and an integer K.

You can apply the given operation on the tree at most once:

  • Select a node x in the tree and consider it as the root of the tree.
  • Select a node y in the tree and update the value of each node in the subtree of y by taking its XOR with K. That is, for each node u in the subtree of node y, set A[u]=A[u]XORK.

Find the maximum sum of values of nodes that are available in the tree, after the above operation is used optimally.

Note

  • Assume 1-based indexing.
  • XOR represents the bitwise XOR operator. 

Input format

  • The first line contains a single integer T that denotes the number of test cases.
  • For each test case:
    • The first line contains an integer N.
    • The second line contains an integer K.
    • The third line contains N space-separated integers denoting array A.
    • Next N1 lines contain two space-separated integers denoting an edge between node u and v.

Output format

For each test case, print the maximum possible sum of values of nodes present in the tree. Print the output for each test case in a new line.

Constraints

1T101N1050A[i]1090K109

 

Sample Input
2
3
4
4 4 4 
1 2
1 3
4
2
5 1 4 2
1 2
2 3
3 4
Sample Output
12
18
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

For test case 1:

  • If the operation is applied on the tree, then the sum of node values will decrease. Thus, it is optimal to not apply operation on the tree.
  • Maximum possible sum of node values is A[1] + A[2] + A[3] = 4 + 4 + 4 = 12.
  • Thus, output 12.

For test case 2:

  • Consider x = 4, for the operation. This means the tree is rooted at node 4.
  • Consider y = 3, for the operation. This means we need to update the values of nodes present in the subtree of node 3 i.e. nodes 1, 2, and 3.
    • A[3] = A[3] XOR K = 4 XOR 2 = 6
    • A[2] = A[2] XOR K = 1 XOR 2 = 3
    • A[1] = A[1] XOR K = 5 XOR 2 = 7
  • Sum of values of all the nodes is A[1] + A[2] + A[3] + A[4] = 6 + 3 + 7 + 2 = 18, which is maximum possible sum.
  • Thus, output 18.
Editor Image

?