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 C (judge verdict: Time Limit Exceeded)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node{
  long key;
  struct node *left;
  struct node *right;
  struct node *p;
}Node;

Node *max = NULL;

Node *insert(Node *root, long key) {
  Node *z = (Node*)malloc(sizeof(Node));
  z->key = key;
  z->p = NULL;
  z->left = NULL;
  z->right = NULL;
  if(max == NULL) {
    max = z;
    return z;
  }
  if(max->key <= z->key) {
    max->right = z;
    z->p = max;
    max = z;
    return root;
  }
  Node *x,*y;
  y = NULL;
  x = root;
  while(x != NULL) {
    y = x;
    if(z->key < x->key) x = x->left;
    else x = x->right;
  }
  z->p = y;
  if(y  == NULL) return z;
  else if(z->key < y->key) y->left = z;
  else y->right = z;
  return root;
}

Node *extract(Node *root) {
  printf("%ld\n",max->key);
  Node *x = max,*y = x->p;
  if(x->left == NULL && x->right == NULL) {
    if(y == NULL) {
      max = NULL;
      free(x);
      return NULL;
    }
    y->right = NULL;
    max = y;
    free(x);
    return root;
  }
  else {
    Node *z;
    z = x->left;
    if(y == NULL) {
      max = z;
      while(max->right != NULL) max = max->right;
      free(x);
      z->p = NULL;
      return z;
    }
    z->p = y;
    y->right = z;
    max = z;
    while(max->right != NULL) max = max->right;	
    free(x);
    return root; 
  }
}


int main()
{
  long key;
  char command[8];
  Node *root = NULL;
  while (1) {
    scanf("%s",command);
    if(strcmp(command,"insert") == 0) {
      scanf("%ld",&key);
      root = insert(root,key);
    }
    if(strcmp(command,"extract") == 0) {
      root = extract(root);
    }
    if(strcmp(command,"end") == 0) break;
  }

  return 0;
}