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 MaximumHeap
  attr_accessor :tree

  def initialize
    @tree = [nil]
    @heapsize = 0
  end

  def insert(key)
    @heapsize += 1
    @tree[@heapsize] = -Float::INFINITY
    heap_increase_key(@heapsize, key)
  end

  def heap_increase_key(i, key)
    raise Exception.new if key < @tree[i]
    @tree[i] = key
    parent = i / 2
    while parent > 0 && i > 0 && @tree[parent] < @tree[i]
      @tree[parent], @tree[i] = @tree[i], @tree[parent]
      i = parent
    end
  end

  def heap_extract_max
    raise Exception.new if @heapsize < 1
    max = @tree[1]
    @tree[1] = @tree[@heapsize]
    @tree.delete_at(@heapsize)
    @heapsize -= 1
    max_heapify(1)
    return max
  end

  def max_heapify(i)
    l = i * 2
    r = i * 2 + 1
    if l <= @heapsize && @tree[l] > @tree[i]
      largest = l
    else
      largest = i
    end
    if r <= @heapsize && @tree[r] > @tree[largest]
      largest = r
    end

    if largest != i
      @tree[i], @tree[largest] = @tree[largest], @tree[i]
      max_heapify(largest)
    end
  end
end

mh = MaximumHeap.new
while ( line = gets.strip ) != "end"
  cmd, key = line.split
  case cmd
  when "insert"
    mh.insert(key.to_i)
  when "extract"
    puts mh.heap_extract_max
  end
end