Cod sursa(job #772474)

Utilizator ionut_blesneagIonut Blesneag ionut_blesneag Data 29 iulie 2012 21:25:17
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
/* HEAPURI */  

#include<stdio.h>
using namespace std;

int n,i;
int h[200001],poz[200001],ind[200001],size,counter;
  

void swap(int q1, int q2)
{int aux=h[q1];
h[q1]=h[q2];
h[q2]=aux;
poz[ind[q1]]=q2;
poz[ind[q2]]=q1;
aux=ind[q1];
ind[q1]=ind[q2];
ind[q2]=aux;

}

void sink(int q)
{int son;
do{son=0;
   if(2*q<=size)
    { son=q<<1;
     if(2*q+1<=size && h[2*q+1]<h[2*q])
     son++;
     if(son && h[son]<h[q])
        {swap(son,q);
         q=son;}  
     else
       son=0;
     }      
   }while(son);

}

void swim(int q)
{int father;
do{father=0;
   if(q>1)
     {father=q>>1;
     if(h[father]>h[q])
      {swap(father,q); 
       q=father;}
     else
      father=0;}   
   }while(father);
}

void insereaza(int q)
{size++;
 counter++;
 h[size]=q;
 poz[counter]=size;
 ind[size]=counter;
 swim(size);}
 
void sterge(int pp)
{int q = poz[pp];
 poz[pp]=0;
 h[q]=h[size];
 size--;
 sink(q);} 

int main()
{freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w",stdout);
int c,p;
scanf("%d",&n);
size=0;
for(i=1; i<=n; i++)
  {scanf("%d",&c);
   if (c!=3)
     {scanf("%d",&p);
      if(c==1)
        insereaza(p);  
      if(c==2)
        sterge(p); }
   else
     printf("%d\n",h[1]);
  }      

return 0;}