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: Accepted)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 2000001
#define MAX 2000000000
int parent(int);
int left(int);
int right(int);
void buildMaxHeap(int*);
void maxHeapify(int*,int);
void swap(int*,int,int);
void printHeap(int*);
void insert(int*,int);
int extract(int*);
int h=0;//size of heap
int main(void)
{
  int arr[N];//array (1-origin)
  char op[10];//operation
  int key;
  arr[0]=MAX+1;
  for(;;)
    {
      scanf("%s",op);
      if(strcmp(op,"insert")==0)
	{
	  scanf("%d",&key);
	  insert(arr,key);
	}
      if(strcmp(op,"extract")==0) printf("%d\n",extract(arr));
      if(strcmp(op,"print")==0) printHeap(arr);//for debugging
      if(strcmp(op,"end")==0) break;
      
    }
  return 0;
}
int parent(int i)
{
  return i/2;
}
int left(int i)
{
  return 2*i;
}
int right(int i)
{
  return 2*i+1;
}
void buildMaxHeap(int *arr)
{
  int i;//counter
  for(i=h/2;i>=1;i--) maxHeapify(arr,i);
}
void maxHeapify(int *arr,int i)
{
  int l=left(i);
  int r=right(i);
  int largest;
  if(i<1) return;
  if(l<=h&&arr[l]>arr[i]) largest=l;
  else largest=i;
  if(r<=h&&arr[r]>arr[largest]) largest=r;
  if(largest!=i)
    {
      swap(arr,i,largest);
      maxHeapify(arr,largest);
    }
}
void swap(int *arr,int x,int y)
{
  int temp;
  temp=arr[x];
  arr[x]=arr[y];
  arr[y]=temp;
}
void printHeap(int *arr)
{
  int i;
  for(i=1;i<=h;i++) printf(" %d",arr[i]);
  printf("\n");
}
void insert(int *arr,int key)
{
  int index;
  h++;
  arr[h]=key;
  for(index=h;index>=1;index=parent(index))
    {
      if(arr[index]<arr[parent(index)]) break;
      maxHeapify(arr,parent(index));
    }
}
int extract(int *arr)
{
  int ret=arr[1];
  arr[1]=arr[h];
  h--;
  maxHeapify(arr,1);
  return ret;
}