Cod sursa(job #1207153)

Utilizator DjokValeriu Motroi Djok Data 12 iulie 2014 13:55:04
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include<fstream>
#include<algorithm>
using namespace std;

int n,poz[200005],h[200005],a[200005],q,aux,op,nr;

void upheap(int x) {
   while(x>1 && a[h[x]]<a[h[x/2]])
   {
     swap(poz[h[x]],poz[h[x/2]]);
     swap(h[x],h[x/2]); x/=2;         
   }  
}

void downheap(int x) {
   int nod=1;
   while(nod)
   {
     nod=0;
     if(2*x<=nr)
     {
       nod=2*x;
       if(2*x+1<=nr && a[h[nod]]>a[h[nod+1]]) ++nod;
       if(a[h[nod]]>=a[h[x]]) nod=0;         
     }        
     if(nod)
     {
       swap(poz[h[nod]],poz[h[x]]);
       swap(h[nod],h[x]); x=nod;
     }
   }  
}

void del(int x) {
   poz[h[nr]]=x; swap(h[x],h[nr]); --nr;
   if(x>1 && a[h[x]]<a[h[x/2]]) upheap(x);
   else downheap(x);  
}

void insert(int x) {
   a[++n]=x; h[++nr]=n; poz[n]=nr;
   upheap(nr);  
}

int main()
{
  ifstream cin("heapuri.in");
  ofstream cout("heapuri.out");
  
  cin>>q;
  
  while(q--)
  {
    cin>>op;
    if(op==1) cin>>aux,insert(aux);
    if(op==2) cin>>aux,del(poz[aux]);        
    if(op==3) cout<<a[h[1]]<<'\n';
  }  
    
 return 0;   
}