Double Queue

Interview

Time limit1sMemory limit128 MB

Summary
Process a stream of add/serve commands maintaining a dynamic set to pop and remove either the maximum or minimum priority client each query.
Level

Medium4 of 10

Topics
Heap, Sorting, Implementation
Solved
No attempts yet

Problem

The newly founded Balkan Investment Group Bank (BIG-Bank) opened a new office in Bucharest, equipped with a modern computing environment provided by IBM Romania and using modern information technologies. As usual, each client of the bank is identified by a positive integer KK and, upon arriving at the bank for some service, receives a positive integer priority PP. One of the inventions of the bank's young managers shocked the software engineer of the serving system: they proposed to break with tradition by sometimes calling to the serving desk the client with the lowest priority instead of the one with the highest priority. Thus, the system receives the following types of request:

  • 0: The system needs to stop serving.
  • 1 K P: Add client KK to the waiting list with priority PP.
  • 2: Serve the client with the highest priority and drop them from the waiting list.
  • 3: Serve the client with the lowest priority and drop them from the waiting list.

Your task is to help the bank's software engineer by writing a program that implements the requested serving policy.

Input

Each line of the input contains one of the possible requests; only the last line contains the stop request (code 0). You may assume that whenever there is a request to add a new client to the list (code 1), no client already in the list has the same identifier or the same priority. An identifier KK is always less than 10610^6, and a priority PP is always less than 10710^7. A client may arrive to be served several times, and may receive a different priority each time.

Output

For each request with code 2 or 3, the program must print, on a separate line of the standard output, the identifier of the served client. If such a request arrives when the waiting list is empty, the program prints zero (00).

Examples3

  1. Example 1

    Input
    2
    1 20 14
    1 30 3
    2
    1 10 99
    3
    2
    2
    0
    
    Expected output
    0
    20
    30
    10
    0
    
  2. Example 2

    Input
    1 1 5
    1 2 10
    1 3 1
    2
    2
    2
    2
    0
    
    Expected output
    2
    1
    3
    0
    
  3. Example 3

    Input
    1 100 50
    1 200 30
    2
    1 300 50
    3
    2
    3
    0
    
    Expected output
    100
    200
    300
    0