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 h = 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 ret = t.(1) in
  t.(1) <- t.(!h);
  decr h;
  let rec max_heapify i =
    let l = left i in
    let r = right i in
    let m = if l <= !h && t.(l) > t.(i) then l else i in
    let m = if r <= !h && t.(r) > t.(m) then r else m in
    if m <> i then begin
      let tmp = t.(i) in t.(i) <- t.(m); t.(m) <- tmp;
      max_heapify m
    end in
  max_heapify 1;
  ret

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

let split str delim =
  let open String in
  let rec doit s acc =
    match
      try Some (rindex s delim) with _ -> None
    with
    | None -> s :: acc
    | Some i ->
      let s1 = sub s 0 i in
      doit s1 (sub s (i + 1) (length s - length s1 - 1) :: acc)
  in doit str []

let () =
  let t = Array.make 2000001 0 in
  let rec doit () =
    match split (read_line ()) ' ' with
    | ["extract"] -> (Printf.printf "%d\n" (extract t); doit ())
    | ["insert"; n] -> (insert (int_of_string n) t; doit ())
    | _ -> ()
  in doit ()