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;
  struct node *max;
}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;
  z->max = z;
  if(root == NULL) {
    max = z;
    return z;
  }
  if(max->key <= z->key) {
    z->p = max;
    max->right = z;
    max = z;
    return root;
  }
  Node *x,*y;
  int t = 0;
  y = NULL;
  x = root;
  while(x != NULL) {
    y = x;
    if(z->key < x->key) {
      x = x->left;
      t = 1;
    }else {
      if(t != 0 && x->max->key <= z->key) x->max = z;
      x = x->right;
    }
  }
  z->p = y;
  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 = max->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 = x->left;
    if(y == NULL) {
      max = z->max;
      free(x);
      z->p = NULL;
      return z;
    }
    z->p = y;
    y->right = z;
    max = z->max;
    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;
}