Cookie Selection

Interview

Time limit1sMemory limit128 MB

Summary
Process a stream of cookie insertions and median requests; each request outputs the upper median of the currently held multiset, supporting up to 600,000 operations.
Level

Medium7 of 10

Topics
Heap, Implementation, Array, Binary search
Solved
No attempts yet

Problem

As the chief programmer at a cookie production plant, you must ensure that every cookie the plant produces and packages meets a very demanding quality standard.

Your production line continuously bakes new cookies and places them in a holding area, where they wait to be packaged. From time to time the packaging unit requests that one cookie be sent from the holding area to be packaged. A packaging request is never issued while the holding area is empty.

What complicates matters are surprise inspections. An inspector may demand that the next few cookies bound for packaging be handed to them instead; if those cookies look (and taste) consistent, you pass the inspection, otherwise you fail.

Fortunately, the plant can measure cookie diameters to a precision of 1 nanometre (nm). To be ready for inspections, on every packaging request you send the cookie with the median diameter among all cookies currently in the holding area. If no cookie has exactly the median diameter, you instead send the smallest cookie whose diameter is larger than the median.

Concretely, sort the cookies in the holding area by ascending diameter. If the holding area contains cc cookies, then on a request you send the cookie at the following position (1-indexed) in the sorted order:

  • if cc is odd, the cookie at position c+12\frac{c+1}{2};
  • if cc is even, the cookie at position c2+1\frac{c}{2}+1.

Input

Each line of input contains one of the following:

  • a positive integer dd — a freshly baked cookie of diameter dd nm has arrived in the holding area;
  • the symbol # — the packaging unit requests that one cookie be sent for packaging.

There are at most 600,000 lines of input, and the holding area is empty before the first cookie arrives. The plant's oven cannot bake a cookie with a diameter larger than 30 centimetres (cm), i.e. 300,000,000 nm.

Output

For each packaging request, output the diameter in nm of the cookie sent for packaging, one per line, in the same order the requests are processed.

Examples4

  1. Example 1

    Input
    1
    2
    3
    4
    #
    #
    #
    #
    
    Expected output
    3
    2
    4
    1
    
  2. Example 2

    Input
    1
    #
    2
    #
    3
    #
    4
    #
    
    Expected output
    1
    2
    3
    4
    
  3. Example 3

    Input
    5
    #
    
    Expected output
    5
    
  4. Example 4

    Input
    10
    10
    #
    #
    
    Expected output
    10
    10