Subtree swap

4

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

You are given an undirected tree with N nodes rooted at node 1. Every node has a value A[i] assigned to it. You are required to answer Q queries of the following type:

  • UVX
    • Select a subtree with U as the root node and subtree with V as the root node and swap their positions. That is, detach both the subtrees and swap their positions.
    • If node U is an ancestor of node V or node V is an ancestor of node U, the above Swap operation is not performed.
    • Find the sum of node values present in the subtree rooted at node X.
    • If the Swap operation is performed, then redo this operation. That is, swap the subtree with U as the root node and subtree with V as the root node.

Determine the required answer for Q queries.

Note

  • Assume 1-based indexing.
  • A node u is said to be an ancestor of node v if node u lies on a simple path between the root and node v.
  • Here, Redo means re-doing the operation performed.

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 N space-separated integers denoting array A.
    • The next N1 line contains two space-separated integers uv denoting an edge between node u and v.
    • The next line contains an integer Q.
    • The next Q lines contain three space-separated integers UVX denoting the query.

Output format

For each test case, print Q space-separated integers denoting the sum of node values present in the subtree rooted at node X after the swap operation is performed. Print the output for each test case in a new line.

Constraints

1T101N,Q1051A[i]1091U,V,XN

 

Sample Input
2
5
4 1 4 2 3
1 2
2 3
2 4
1 5
1
3 5 2
5
4 3 1 56 5
1 2
2 3
3 4
4 5
2
1 5 2
3 5 3 
Sample Output
6
65 62
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

For first test case

  • For query 1: U = 3, V = 5, X = 2
    • After swap operation, edges will be [(1, 2), (2, 5), (2, 4), (1, 3)]
    • Nodes in the subtree rooted at node 2 are 2, 4, 5.
    • Sum of node values is 1 + 2 + 3 = 6.
    • Redo the swap operation, edges will be [(1, 2), (2, 3), (2, 4), (1, 5)].
  • Thus, the required answer is [6].

For second test case

  • For query 1: U = 1, V = 5, X = 2
    • Swap operation is not performed as node U is the ancestor of node V.
    • Nodes in the subtree rooted at node 2 are 2, 3, 4, 5.
    • Sum of node values is 3 + 1 + 56 + 5 = 65.
  • For query 2: U = 3, V = 5, X = 3
    • Swap operation is not performed as node U is the ancestor of node V.
    • Nodes in the subtree rooted at node 3 are 3, 4, 5.
    • Sum of node values is 1 + 56 + 5 = 62.
  • Thus, the required answer is [65, 62].
Editor Image

?