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: Time Limit Exceeded)

class Node
  include Comparable

  def initialize(id, key)
    @id = id
    @key = key
  end

  def <=>(other)
    return 1 if (other == nil)
    return @key <=> other.key
  end

  DUMMY = Node.new(-1, -2_000_000_001)

  attr_accessor :id, :key
end

def maxHeapify(array, i)
  left = (i*2 < array.size) ? array[i*2] : Node::DUMMY
  right = (i*2+1 < array.size) ? array[i*2+1] : Node::DUMMY
  max = [array[i], left, right].sort_by{|x| x.key}.pop
  max_key = max.key
  if (left.key == max.key) then
    left.key = array[i].key
    array[i].key = max_key
    maxHeapify(array, left.id)
  elsif (right.key == max.key) then
    right.key = array[i].key
    array[i].key = max_key
    maxHeapify(array, right.id)
  end
end

def buildMaxHeap(array)
  ((array.size-1) / 2).downto(1) do |i|
    maxHeapify(array, i)
  end
end

def insert(array, i)
  array << Node.new(array.size, i)
  buildMaxHeap(array)
end

def extract(array)
  if (array.size >= 2) then
    max = array[1].key
    array.delete_at(1)
    array.each_with_index do |x, i|
      if x != nil then
        x.id = i
      end
    end
    buildMaxHeap(array)
    return max
  else
    return nil
  end
end

# main
array = [nil]
while line = gets do
  inputs = line.chomp.split
  if (inputs[0] == 'insert') then
    insert(array, inputs[1].to_i)
  elsif(inputs[0] == 'extract') then
    puts extract(array)
  else
    break
  end
end