New Barns
Time limit2sMemory limit512 MB
Process online queries that add a leaf to a growing forest or ask for the eccentricity (distance to the farthest node) of a given node.
- Level
Hard8 of 10
- Topics
- Tree, Graph, BFS, Dynamic programming
- Solved
- No attempts yet
Problem
Farmer John notices that his cows tend to get into arguments if they are packed too closely together, so he wants to open a series of new barns to spread them out.
Whenever John builds a new barn, he connects it with at most one bidirectional pathway to a barn that already exists. To make sure his cows are spread far enough apart, he sometimes wants the distance from a certain barn to the farthest barn reachable from it. The distance between two barns is the number of pathways you traverse to go from one to the other.
John gives () queries in total, each either a build query or a distance query. In a build query, John builds one barn and links it with at most one previously built barn. In a distance query, John asks for the distance from a certain barn to the farthest barn reachable from it along the pathways. The queried barn has already been built. Answer all of the queries.
Input
The first line contains the integer . Each of the next lines contains one query, either "B p" or "Q k", telling you to build a barn and connect it with barn , or to report the farthest distance from barn . If , the new barn is connected to no other barn. Otherwise is the index of a barn that has already been built. Barn indices start from , so the first barn built is barn , the second is barn , and the numbering continues that way.
Output
Print one line for each distance query. A barn that is connected to no other barn has farthest distance .
Note
The input of the first example corresponds to this network of barns.
(1)
\
(2)---(4)
/
(3)
Query 1 builds barn . Query 2 asks for the distance from barn to the farthest connected barn. Barn is connected to no other barn, so the answer is . Query 3 builds barn and connects it to barn , and query 4 builds barn and connects it to barn . Query 5 asks for the farthest barn from barn . The farthest one is barn at distance , so the answer is . Query 6 builds barn and connects it to barn . Query 7 asks for the farthest barn from barn . Barns , and all sit at distance , so the answer is .