Break And Fix The Tree
Chef is playing a game, and to win the prize, he must complete it. But he is busy arranging meals for the vortex party, so he asked you the play the game in his place. The game is as below:
You are given a rooted tree of size rooted at node , where each node has a value assigned to it. Define as the parent of node . You have to perform queries of the following type on the tree:
- : Break the edge between node and in the tree, and attach as a child of (note that this means after this operation). It is guaranteed that is a leaf node of the tree.
- : Change the value on node to (i.e. assign ).
- : Calculate the sum of values of nodes on the path from to .
Note that the queries are accumulative, meaning the changes made in each query is persisted for the following queries.
Input Format
- The first line of the input contains an integer - the number of nodes in the tree.
- The next line contains space-separated integers - the parents node of to .
- The next line contains space-separated integers - the initial values of the nodes.
- The next line contains an integer - the number of queries.
- Each of the next lines contains a query as described in the statement.
Output Format
For each query of type , output on a new line the sum of values of nodes on the path from to .
Constraints
Sample Input 1
5
1 1 2 2
1 2 3 4 5
6
3 4 5
1 4 3
1 5 3
1 2 4
2 4 10
3 2 5
Sample Output 1
11
20
Explanation
- Initially, the tree is
- For first query, the path followed is . Therefore the sum of values is .
- After updating the tree according to second query, it becomes
After updating the tree according to third query, it becomes
After updating the tree according to fourth query, it becomes
After updating the tree according to fifth query, it becomes
The path for the sixth query is . Therefore the sum of values is .
Comments
Post a Comment