Cod sursa(job #296082)

Utilizator bacerandreiBacer Andrei bacerandrei Data 4 aprilie 2009 10:41:21
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream.h>   
#define nmax 200005   
  
ifstream fin("heapuri.in");   
ofstream fout("heapuri.out");   
  
long h[nmax] , poz[nmax] , n , nr;
long val[nmax];



int sift(int k)
{
  int son;
  do
   {
    son=0;
     if (2*k<=n)
      {
       son=2*k;
	if (son+1<=n && val[h[son+1]]<val[h[son]])
	 son++;
      }
    if (val[h[k]]<=val[h[son]])
      son=0;
    else
      if (son>0)
       {
	long aux=h[k];
	h[k]=h[son];
	h[son]=aux;

	 poz[h[k]]=k;
	 poz[h[son]]=son;

       k=son;
     }
}while (son);

return k;
}



void percolate(long k)
{long aux;

 while (k>1 && val[h[k/2]]>val[h[k]])
  {
    aux=h[k/2];
    h[k/2]=h[k];
    h[k]=aux;

     poz[h[k/2]]=k/2;
     poz[h[k]]=k;

    k=k/2;
   }
}




void insert(long x)
{
  n++;
  nr++;
   val[nr]=x;
   h[n]=nr;
  poz[nr]=n;
 percolate(n);
}


void cut(long k)
{
  h[k]=h[n];
  --n;

 if (k>1 && h[k]<h[k/2])
    percolate(k);
  else
    sift(k);
}



int main()
{
  long x,m,key;
   fin>>m;
  for (long i=1;i<=m;i++)
  {
    fin>>key;
   if (key==1)
    {
      fin>>x;
      insert(x);
    }
   if (key==2)
    {
      fin>>x;
      cut(poz[x]);
      poz[x]=0;
    }
   if (key==3) fout<<val[h[1]]<<'\n';
   }


  fout.close();
 return 0;
}