Cod sursa(job #260863)

Utilizator drag0shSandulescu Dragos drag0sh Data 17 februarie 2009 17:23:06
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <stdio.h>

#define maxn 200010
#define IN "heapuri.in"
#define OUT "heapuri.out"

FILE *fin=fopen(IN,"r");
FILE *fout=fopen(OUT,"w");

int n,l,nr;
int a[maxn],heap[maxn],pos[maxn];

void push(int);
void pop(int);

int main()
{
 int i,x,cod;

 fscanf(fin,"%d ",&n);

 for(i=1;i<=n;i++)
 {
  fscanf(fin,"%d ",&cod);
  
  if(cod<3)
   fscanf(fin,"%d ",&x);

   if(cod==1)
   {
    l++;
    nr++;
	a[nr]=x;
	heap[l]=nr;
	pos[nr]=l;

    push(l);
   }

   if(cod==2)
   {
    a[x]=-1;
	push(pos[x]);

    pos[heap[1]]=0;
    heap[1]=heap[l];
    l--;
	pos[heap[1]]=1;
	
	if(l>1)
     pop(1);
   }

   if(cod==3)
    fprintf(fout,"%d\n",a[heap[1]]);
  }

 return 0;
}

void push(int x)
{
 int aux;

 while(x/2 && a[heap[x]]<a[heap[x/2]])
 {
  aux=heap[x];
  heap[x]=heap[x/2];
  heap[x/2]=aux;

  pos[heap[x]]=x;
  pos[heap[x/2]]=x/2;
  x/=2;
 }
}

void pop(int x)
{
 int aux,y=0;

 while (x!=y)
 {
  y=x;

  if(y*2<=l && a[heap[x]]>a[heap[y*2]])
   x=y*2;
  if(y*2+1<=l && a[heap[x]]>a[heap[y*2+1]])
   x=y*2+1;

  aux=heap[x];
  heap[x]=heap[y];
  heap[y]=aux;

  pos[heap[x]]=x;
  pos[heap[y]]=y;
 }
}