Cod sursa(job #772473)

Utilizator ionut_blesneagIonut Blesneag ionut_blesneag Data 29 iulie 2012 21:20:01
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
/* HEAPURI */  

#include<fstream>
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

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

/*void afiseaza()
{g<<"*****************"<<endl;
for(int psi=1; psi<=size; psi++)
  g<<h[psi]<<" ";
  g<<endl; 
for(int psi=1; psi<=counter; psi++)  
  g<<poz[psi]<<" "; 
 g<<endl<<"*****************"<<endl<<endl<<endl;} */
  

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()
{int c,p;
f>>n;
size=0;
for(i=1; i<=n; i++)
  {f>>c;
   if (c!=3)
     {f>>p;
      if(c==1)
        insereaza(p);  
      if(c==2)
        sterge(p); }
   else
     g<<h[1]<<endl;
  }      
f.close();
g.close();
return 0;}