Team Queue
InterviewTime limit1sMemory limit128 MB
Simulate a team queue where each new element cuts in behind its own teammates, if any, and otherwise joins the tail; print every dequeued element.
- Level
Medium5 of 10
- Topics
- Queue, Hash map, Simulation, Implementation
- Solved
- No attempts yet
Problem
Queues and priority queues are data structures familiar to most computer scientists. The team queue, however, is less well known even though it appears often in everyday life. For example, the line in front of the cafeteria at lunch time is a team queue.
In a team queue, every element belongs to a team. When a new element enters the queue, it first scans the queue from front to back to see whether any of its teammates (elements of the same team) are already present. If so, it enters the queue immediately behind them. If not, it joins the queue at the tail and becomes the new last element. Dequeuing works as in an ordinary queue: elements are processed from front to back in the order they occupy the team queue.
Write a program that simulates such a team queue.
Input
The input consists of one or more test cases. Each test case begins with the number of teams (). Then team descriptions follow; each description consists of the number of elements in the team followed by those elements. Elements are integers in the range to , and a team may contain up to elements.
A list of commands then follows. There are three kinds of commands:
ENQUEUE x— put element into the team queue.DEQUEUE— process the front element and remove it from the queue.STOP— end of the test case.
The input ends when is .
Note: a single test case may contain up to 200000 commands, so the team queue must be implemented efficiently — both enqueuing and dequeuing should take constant time.
Output
For each test case, first print a line Scenario #k, where is the number of the test case (starting from ). Then, for each DEQUEUE command, print the dequeued element on its own line. Separate the outputs of consecutive test cases with a single blank line.