Tree
Time limit2sMemory limit512 MB
Maintain a rooted tree under vertex deletions (children reparent to grandparent) and answer distance queries between two live vertices.
- Level
Hard8 of 10
- Topics
- Tree, DFS, Segment tree, Dynamic programming
- Solved
- No attempts yet
Problem
You are given a rooted tree with vertices. The vertices are numbered from 1 to , and vertex 1 is the root. A rooted tree is a connected undirected graph with one vertex chosen as the root. For every vertex, the neighbor closest to the root is its parent, and the other neighbors are its children. The root has no parent.
Two kinds of queries are processed in the given order.
The first kind removes a vertex. When vertex is removed, every child of becomes a child of the parent of . The root is never removed.
The second kind asks for a distance. It is the length of the path between two vertices in the current tree, counted as the number of edges on that path.
Answer every distance query.
Input
The first line contains the number of vertices in the initial tree ().
The second line contains the parents of vertices in this order (). When is 1, the second line is empty.
The third line contains the number of queries ().
Each of the next lines holds one query. A query starts with an integer that is either 1 or 2. If that integer is 1, two integers and follow (), and you must report the distance between and in the current tree. If it is 2, one integer follows (), and vertex must be removed.
The initial tree is always valid. Every vertex named in a query is still present, and the root is never given as a vertex to remove.
Output
For each query that starts with 1, print the distance between the two vertices on its own line.