Cod sursa(job #1070907)

Utilizator MihaiBunBunget Mihai MihaiBun Data 2 ianuarie 2014 12:15:42
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <cstdio>

using namespace std;
int i,n,op,x,hap[400005],t,k,j,poz[400005],q[400005],min;

void inter(int a,int b)
{
         t=hap[a];
         hap[a]=hap[b];
         hap[b]=t;
         t=poz[q[a]];
         poz[q[a]]=poz[q[b]];
         poz[q[b]]=t;
         t=q[a];
         q[a]=q[b];
         q[b]=t;
};

void up(int m)
{
  if (m>1)
     if (hap[m/2]>hap[m])
       {
         inter(m/2,m);
         up(m/2);
       };
};

void insereaza(int x)
{
    k++;
    hap[k]=x;
    poz[i]=k;
    q[k]=i;
    up(k);
};

void down(int m)
{
   if (2*m+1<=k)
        {
           if ((hap[m]>hap[2*m])&&(hap[m]>hap[2*m+1]))
                                {
                                   if (hap[2*m]>hap[2*m+1])min=2*m+1;
                                                      else min=2*m;
                                   inter(m,min);
                                   down(min);
                                }
                          else {
                                 if (hap[2*m]<hap[m]){inter(m,2*m);down(2*m);};
                                 if (hap[2*m+1]<hap[m]){inter(m,2*m+1);down(2*m+1);};
                               };
        }
       else if ((2*m<=k)&&(hap[m]>hap[2*m])){inter(m,2*m);down(2*m);}
};

void sterge (int x)
{
  j=poz[x];
  hap[j]=hap[k];
  poz[q[k]]=j;
  q[j]=k;
  k--;
  if ((j>1)&&(hap[j]<hap[j/2]))up(j);
                         else down(j);
};

int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    k=0;//dim heap
    for (i=1;i<=n;i++)
    {
      scanf("%d",&op);
      if (op==1){scanf("%d",&x);insereaza(x);}
      else  if (op==2){scanf("%d",&x);sterge(x);}
                else printf("%d\n",hap[1]);
    };
    return 0;
}