Repair this tree

4

4 votes
Advanced Data Structures, Data Structures, Hard, Segment Trees
Problem

You are given a rooted tree T of n nodes and a graph G of n nodes. Initially, the graph G has no edges. There are two types of queries:

  • 1 x y w: Add an edge of weight w between nodes x and y in G
  • 2 v p: Consider that the edge between v and its parent in T is deleted which decomposes T into 2 connected components. You need to find the sum of weights of all edges like x in G such that:
    • The weight of x is divisible by p
    • If an edge is added in T between the same endpoints as x then again we will get a tree (it will connect the two components). Note that the edge is deleted only for that particular query. 

Input:

  • First line: Two integers n,q(1n200 000,1q300 000)
  • Second line: n1 integers where (i)th integer is the number of the parent of (i+1)th node. 1 is the root of the tree.
  • Next q lines: Contains a description of queries. One query per line as described in the question (1w,p1 000 000,1x,yn,2vn), p is prime
  • The graph G may have self-loops and multiple edges.
  • Queries are encrypted, hence you have to answer queries online. If lastAns is the answer of the last query of type 2 (zero if not present), then you must decrypt queries as follows:
    • 1 x y must be decrypted as x=(x+lastAns1)modn+1,y=(y+lastAns1)modn+1
    • 2 v must be decrypted as v=(v+lastAns1)mod(n1)+2.

Output:
For each query of the second type, print the answer in a seperate line.

Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

Decrypted queries:

1 4 2 6
1 4 3 12
1 2 2 5
2 2 2
2 4 3
2 2 3
1 3 5 2
1 2 1 7
2 3 3
1 5 1 8
2 3 7
 

Editor Image

?