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 OCaml (judge verdict: Accepted)

let last_i = ref 0

let parent i = int_of_float (floor (float_of_int i) /. 2.)

let left i = 2*i

let right i = 2*i + 1

let extract (t : int array) =
  let rec max_heapify i =
    let l = left i in
    let r = right i in
    let m = if l <= !last_i && t.(l) > t.(i) then l else i in
    let m = if r <= !last_i && t.(r) > t.(m) then r else m in
    if i = m then ()
    else begin
      let tmp = t.(i) in
      t.(i) <- t.(m);
      t.(m) <- tmp;
      max_heapify m
    end in
  let ret = t.(1) in
  t.(1) <- t.(!last_i);
  decr last_i;
  max_heapify 1;
  ret

let insert x (t : int array) =
  let rec doit i =
    let p = parent i in
    if i <= 1 || t.(p) >= t.(i) then ()
    else begin
      let tmp = t.(i) in
      t.(i) <- t.(p);
      t.(p) <- tmp;
      doit p
    end in
  incr last_i;
  t.(!last_i) <- x;
  doit !last_i

let () =
  let t = Array.make 2000001 0 in
  let rec doit () =
    let op = Scanf.scanf "%s " (fun i -> i) in
    if op = "end" then ()
    else if op = "extract" then begin
      extract t |> Printf.printf "%d\n";
      doit ()
    end else begin
      insert (Scanf.scanf "%d " (fun i -> i)) t;
      doit ()
    end in
  doit ()