
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains one integer ‘N’, denoting the number of nodes in the tree.
The following line contains an array ‘C’ of ‘N’ spaced integers denoting the number of coins attached to each node.
The following line ‘N’ - 1 contains two integers ‘x’ and ‘y’ denoting that there is an edge between node ‘x’ and node ‘y’.
For each test case, print a single integer denoting the maximum coins you can collect.
You don't have to take input or output you just have to complete the function.
1 <= T <= 5
1 <= N <= 10^5
1 <= C[i] <= 10^9
1 <= x, y <= N
Time Limit: 1 sec
Now let’s take a simple tree.
Now if we take coins at node 1 then for sure we can not take coins present at nodes 2 and 3, but if we skip node 1 then, we have two options for each of the other two nodes .i.e we can either take or skip them.
To generalise this, we can say that if we take the parent node, we need to skip all its direct children nodes and if we skip the parent node, we can either take its children node or skip it.
Let F(x, b) be a recursive function that takes a node and a boolean value and depending upon the boolean value it returns the maximum number of coins we can take from the subtree of that node.
F(x, 1) = ‘C[x]’ + F(y1, 0) + F(y2, 0) + F(y3, 0) + … F(yn, 0).
F(x, 0) = max(F(y1, 0), F(y1, 1) + max(F(y2, 0), F(y2,1) + .. max(F(yn,0), F(yn,1).
Since we need to find the maximum number of coins we can take from the whole tree so the final answer is going to be the maximum of F(root,0) and F(root,1).
Let’s look at how the brute force approach will work on the following tree.
After calling F(1,1) we get
After calling F(1,0) we get,
Notice that we are recalculating many states which were earlier visited such as (3,0). We can avoid such states by memorising them and directly returning the values when we reach an already visited state.