Jas the Worm
Time limit1sMemory limit128 MB
A rooted tree grows one leaf at a time while Jas steps once toward each queried vertex, and the task reports his landing vertex after every move.
- Level
Medium5 of 10
- Topics
- Tree, Binary search
- Solved
- No attempts yet
Problem
Jas is a little worm who has decided to make his home in a tree. The tree he picks is very young: at the moment Jas moves in, it has only a single vertex, numbered .
After that, both the tree and Jas go about their own business.
- The tree keeps growing, sprouting new vertices one at a time. An event written
D xmeans a new vertex is added to the tree and attached to a vertex that is already present. - Jas strolls around the tree, each step moving from his current vertex to one of its direct neighbours. An event written
J xmeans Jas moves one step in the direction of vertex . Note that the vertex he actually reaches is not given, only the vertex he is heading toward.
Newly attached vertices are numbered with consecutive integers: the first one added becomes vertex , the next becomes vertex , and so on. Jas always begins at vertex .
Hektor is watching all of this and, after every move Jas makes, wants to know where Jas currently is. Can you help him?
Input
The first line contains an integer (), the number of test sets. The test sets are described one after another.
For each test set, the first line contains an integer (), the number of events. Each of the following lines describes one event in one of two forms:
D x(with the current number of vertices in the tree): a new vertex is attached to vertex .J x(with the current number of vertices in the tree): Jas moves one step toward vertex .
If, when a J x event arrives, Jas is already standing at vertex , then he stays where he is, and that unchanged position must still be reported.
Output
For each test set, print one line for every J x event, in the order the events occur. On each such line print the number of the vertex where Jas ends up right after that move.
Hint
Take the sample. First the tree sprouts four new vertices, so it has in total: vertices form the chain , and vertex is also attached to vertex .
Then Jas starts to wander. His first move is toward vertex , so he steps to vertex . The next two moves toward vertex take him first to vertex and then to vertex . The following two moves are toward vertex : Jas has to walk back to vertex to reach it. Finally the tree grows a sixth vertex attached to vertex ; Jas heads that way, up the tree, and arrives at vertex .