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
  attr_accessor :key, :left, :right, :parent
  def initialize key
    @key = key
  end
  def extract
    if right
      right.extract
    else
      puts $key=key
      delete $root
    end
  end
  def in
    left.in if left
    $a << self
  end
end

def insert
  z = Node.new $key
  x = $root
  while x
    y = x
    x = z.key < x.key ? x.left : x.right
  end
  z.parent=y
  unless y
    $root = z
  else
    z.key < y.key ? y.left = z : y.right = z
  end
end

def find root
  if root == nil
    puts 'no'
  elsif $key == root.key
    puts 'yes'
  elsif $key < root.key
    find root.left
  else
    find root.right
  end
end

def delete1 parent, node
  if parent
    if l = parent.left
      $key == l.key ? parent.left = node : parent.right = node
    else
      parent.right = node
    end
  else
    $root = node
  end
  node.parent = parent
end
def delete root
  left = root.left
  right = root.right
  if $key == root.key
    parent = root.parent
    if (left || right) == nil
      if l = parent.left
        $key == l.key ? parent.left = nil : parent.right = nil
      else
        parent.right = nil
      end
    elsif left && right
      $a=[]
      right.in
      root.key = $key = $a[0].key
      delete $a[0]
    elsif left
      delete1 parent, left
    else
      delete1 parent, right
    end
  elsif $key < root.key
    delete left
  else
    delete right
  end
end

begin
  command, $key = gets.split
  $key = $key.to_i
  case command
  when 'insert'
    insert
  when 'extract'
    $root.extract
  end
end while command != 'end'