Cod sursa(job #606564)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 4 august 2011 19:38:15
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include<fstream.h>
#define N 200001
long h[N],n,k,i,r,j,p[N],v[N],z;

void add(long h[N],long *n,long p[N],long v[N],long j)
{h[++(*n)]=j,p[j]=(*n);
long t=(*n),k=h[(*n)],x;
while(t>1&&v[k]<v[h[t/2]])
      {x=h[t],h[t]=h[t/2],h[t/2]=x,x=p[h[t]];
      p[h[t]]=p[h[t/2]],p[h[t/2]]=x,t/=2;}}

void del(long h[N],long *n,long k,long p[N],long v[N])
{long s,aux,x,y,z,t=h[k];
h[k]=h[(*n)],h[(*n)]=t;
z=p[h[(*n)]],p[h[(*n)--]]=p[h[k]];
p[h[k]]=z;
if(k>1&&v[h[k]]<v[h[k/2]])
      {x=h[k];
      while(k>1&&v[x]<v[h[k/2]])
              {t=p[h[k]],p[h[k]]=p[h[k/2]],p[h[k/2]]=t;
              t=h[k],h[k]=h[k/2],h[k/2]=t,k/=2;}}
else
      {do
              {s=0;
              if(2*k<=(*n))
                      {s=2*k;
                      if(2*k<(*n)&&v[h[2*k+1]]<v[h[2*k]])
                              s=2*k+1;
                      if(v[h[s]]>=v[h[k]])
                              s=0;}
              if(s)
                      {x=h[k],h[k]=h[s],h[s]=x;
                      t=p[h[s]],p[h[s]]=p[h[k]],p[h[k]]=t,k=s;}}
      while(s);}}

int main()
{ifstream f("heapuri.in");
ofstream g("heapuri.out");
f>>n;
while(n--)
      {f>>z;
      if(z==3)
              g<<v[h[1]]<<"\n";
      else
              {f>>r;
              if(z==1)
                      {v[++j]=r;
                      add(h,&k,p,v,j);}
              else
                      del(h,&k,p[r],p,v);}}
return 0;}