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 N rooted at node 1, where each node i has a value Vi assigned to it. Define Pu as the parent of node u. You have to perform queries of the following type on the tree:

  1. 1XW: Break the edge between node X and PX in the tree, and attach X as a child of W (note that this means PX=W after this operation). It is guaranteed that X is a leaf node of the tree.
  2. 2XK: Change the value on node X to K (i.e. assign VXK).
  3. 3XY: Calculate the sum of values of nodes on the path from X to Y.

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 N - the number of nodes in the tree.
  • The next line contains N1 space-separated integers P2,P3,,PN - the parents node of 2 to N.
  • The next line contains N space-separated integers V1,V2,,VN - the initial values of the nodes.
  • The next line contains an integer Q - the number of queries.
  • Each of the next Q lines contains a query as described in the statement.

Output Format

For each query of type 3, output on a new line the sum of values of nodes on the path from X to Y.

Constraints

  • 2N105
  • 1PiN
  • 109Vi109
  • 1Q105
  • 1X,Y,WN
  • XW
  • 109K109

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

image original

  • For first query, the path followed is 425. Therefore the sum of values is 4+2+5=11.
  • After updating the tree according to second query, it becomes

image

  • After updating the tree according to third query, it becomes

    image

  • After updating the tree according to fourth query, it becomes

    image

  • After updating the tree according to fifth query, it becomes

    image

  • The path for the sixth query is 2435. Therefore the sum of values is 2+10+3+5=20.

Comments

Popular posts from this blog

Walmart Sparkplug 2022 | 150 students will be selected for summer internship | ₹1-1.1 lakh monthly

Flipkart Runway: Season 3 | 2025 | Internship

Python for Data Science NPTEL Assignment Solutions Week 4 2022

GATE 2022 Answer Key Release Date Announced; Details Here