Queue
Time limit2sMemory limit32 MB
Simulate people repeatedly leaving a queue and reinserting before another person, then answer position and label lookup queries efficiently using a balanced structure like a Fenwick tree or order-statistics tree.
- Level
Medium7 of 10
- Topics
- Segment tree, Binary search, Simulation, Sorting
- Solved
- No attempts yet
Problem
Fans hoping to buy tickets for this year's World Cup final in Germany have formed a long queue in front of the ticket office.
As the fans arrived, they were labeled with successive integers in arrival order: 1, 2, 3, and so on. The person at the front of the queue is labeled 1, the next is labeled 2, and so on. Initially the person labeled stands at position .
While waiting through the night, some fans needed to use the restroom. Whenever a person uses the restroom, they step out of the queue and, upon returning, step back in immediately in front of one specific person (not necessarily at their previous spot). There is only one restroom, so no one steps out before the previous person has returned; hence at most one person is missing from the queue at any moment.
During the night there were restroom visits in total. Each visit is given by two integers and , meaning the person labeled stepped out of the queue and stepped back in immediately in front of the person labeled .
After all visits are finished, you must answer questions. Each question is one of the following:
P X: report the current position of the person labeled .L X: report the label of the person currently at position .
The front of the queue is position 1, the next is position 2, and so on.
Input
The first line contains the number of restroom visits ().
Each of the following lines contains two different integers and (, ), describing one restroom visit.
The next line contains the number of questions ().
Each of the following lines contains a single uppercase character (P or L) and an integer (), describing one question.
Output
Print lines.
The -th line must contain a single integer: the answer to the -th question.
If the question has the form P X, print the current position of the person labeled . If it has the form L X, print the label of the person currently at position .