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 swap i j t = let tmp = t.(i) in t.(i) <- t.(j); t.(j) <- tmp

let extract (t : int array) =
  let ret = t.(1) in
  t.(1) <- t.(!last_i);
  decr last_i;
  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
      swap i m t;
      max_heapify m
    end in
  max_heapify 1;
  ret

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

let split_on_char sep s =
  let open String in
  let r = ref [] in
  let j = ref (length s) in
  for i = length s - 1 downto 0 do
    if get s i = sep then begin
      r := sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
  sub s 0 !j :: !r

let () =
  let t = Array.make 2000001 0 in
  while true do
    match read_line () |> split_on_char ' ' with
    | ["extract"] -> extract t |> Printf.printf "%d\n"
    | ["insert"; n] -> insert (int_of_string n) t
    | _ -> exit 0
  done