Infestation
Time limit2sMemory limit1024 MB
Process infest, ultrasound, and clear events on a rooted tree, and report how many infested nodes lie in the subtree of each queried node.
- Level
Hard8 of 10
- Topics
- Tree, Segment tree, Simulation
- Solved
- No attempts yet
Problem
Rats are invading Lora's mansion. Luckily, the rooms of the mansion can be described as a rooted tree with nodes, numbered from 1 to , with node 1 as the root.
Initially, no node is infested. Various events then happen one after another, each being one of the following 4 types:
1 X: Node X becomes infested.2 X: Lora wants to eliminate the rats in all nodes on the path from node 1 to node X (inclusive) by using ultrasound in all of them at the same time. When ultrasound is used in an infested node, the rats in it scatter, and each of its direct neighbours that does not use ultrasound becomes infested. The nodes where ultrasound is used stop being infested. After the rats have moved, the ultrasound stops, so the cleared nodes may become infested again in future events.3 X: Lora hires professionals to clear node X and its direct children. After this event, node X and its direct children are no longer infested.4 X: Lora wants the total number of infested nodes in the subtree of node X.
The subtree of node X is the set of nodes that contains X and all of its direct and indirect descendants.
Input
The first line contains a single integer , the number of nodes. The second line contains integers, where the -th integer is , the parent of node . The third line contains the number of events . Each of the next lines contains two integers describing one event.
Output
For every event of type 4, print one line containing one integer: the number of infested nodes in the subtree.
Constraints
Hint
The events have the following effects. Event 1 3 infests node 3. Event 2 5 uses ultrasound on nodes 1, 3 and 5, the path from node 1 to node 5. Node 3 is infested and its only neighbour without ultrasound is node 4, so node 3 stops being infested and node 4 becomes infested. Event 4 1 asks about the whole tree, and the only infested node is 4. Event 1 1 infests node 1. Event 2 1 uses ultrasound on node 1, so nodes 2 and 3 become infested while node 1 stops being infested. Event 4 3 asks about nodes 3, 4 and 5, of which 3 and 4 are infested. Event 3 1 clears nodes 1, 2 and 3, so they are no longer infested. Event 4 3 asks about nodes 3, 4 and 5, of which only node 4 is infested.