Cod sursa(job #402182)

Utilizator preda_alexandruPreda Alexandru preda_alexandru Data 23 februarie 2010 16:36:20
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include<stdio.h>

int h[200001],v[200001],ord[200001],c,n,m;

void sift(int k)
{
int min,poz,aux;
while(2*k<=m){
             min=v[h[2*k]];
             poz=2*k;
             if(2*k+1<=m && v[h[2*k+1]]<min){
                                            min=v[h[2*k+1]];
                                            poz=2*k+1;
                                            }
             if(v[h[k]]>v[h[poz]]){
                                  aux=h[k];
                                  h[k]=h[poz];
                                  h[poz]=aux;
                                  ord[h[poz]]=poz;
                                  ord[h[k]]=k;             
                                  }
             else break;
             k=poz;
             }
}

void percolate(int k)
{
int aux;
while(k>1 && v[h[k]]<v[h[k/2]]){
                               aux=h[k];
                               h[k]=h[k/2];
                               h[k/2]=aux;
                               ord[h[k]]=k;
                               ord[h[k/2]]=k/2;
                               k=k/2;
                               }    
}

void insert(int x)
{
int i;
c++;
m++;
v[c]=x;
ord[c]=m;
h[m]=c;
for(i=n/2;i>=1;i--)sift(i);
}

void del(int k)
{
h[ord[k]]=h[m--];
if(k>1 && v[h[k]]<v[h[k/2]])percolate(ord[k]);
else sift(ord[k]);
}   

int main()
{
int i,x,o;
freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w",stdout);
scanf("%d",&n);
for(i=1;i<=n;i++){
                 scanf("%d",&o);;
                 if(o==1){
                         scanf("%d",&x);;
                         insert(x);
                         }
                 else if(o==2){
                              scanf("%d",&x);;
                              del(x);
                              }
                      else printf("%d\n",v[h[1]]);
                 }
return 0;
}