Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Priority Queue

A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations:

$insert(S, k)$: insert an element $k$ into the set $S$

$extractMax(S)$: remove and return the element of $S$ with the largest key

Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$.
The priority queue manages a set of integers, which are also keys for the priority.

Input

Multiple operations to the priority queue $S$ are given. Each operation is given by "insert $k$", "extract" or "end" in a line. Here, $k$ represents an integer element to be inserted to the priority queue.

The input ends with "end" operation.

Output

For each "extract" operation, print the element extracted from the priority queue $S$ in a line.

Constraints

The number of operations $\leq 2,000,000$

$0 \leq k \leq 2,000,000,000$

Sample Input 1

insert 8
insert 2
extract
insert 10
extract
insert 11
extract
extract
end

Sample Output 1

8
10
11
2

Solution in Ruby (judge verdict: Wrong Answer)

class BinHeap
  def initialize(n,buf=nil,max=nil)
    @size=n
    @buf=buf||Array.new(n)
    @max=max||1
  end
  def add(n)
    a=@buf[i=@max]=n
    @max+=1
    while i>1 && a>b=@buf[i/2]
      @buf[i],@buf[i/2]=b,a
      a=b
      i/=2
    end
  end
  def get
    ret=@buf[1]
    a=@buf[i=1]=@buf[l=@max-=1]
    while (c=i*2)<l
      c+=1 if c+1<l && @buf[c]>@buf[c+1]
      if a<b=@buf[c]
        @buf[c],@buf[i]=a,b
        i=c
        a=b
      else
        break
      end
    end
    ret
  end
  def dup
    BinHeap.new(@size,@buf.dup,@max)
  end
  def buf
    @buf
  end
end

pq=BinHeap.new(2000000)
while gets
  op,arg = $_.split
  case op
  when "insert"
    pq.add arg.to_i
  when "extract"
    p pq.get
  when "end"
  end
end