Cod sursa(job #337377)

Utilizator Bogdan_CCebere Bogdan Bogdan_C Data 3 august 2009 15:18:39
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include<cstdio>
using namespace std;
int heap[2*200000+1],n,i,j,l,r,lheap,poz[200001],poz2[200001],nrcr,x;
int left(int i)
 {return 2*i;}
 int right (int i)
 {return 2*i+1;}
 int parent(int i)
 {return i/2;}



void minheapify(int i)
{if(i<lheap )
 {int min=i;
  if(2*i<=lheap) {l=left(i);
                  if(heap[l]<heap[min]) min=l;
                  if((2*i+1<=lheap)) {r=right(i);} if(heap[r]<heap[min]) min=r;}
    if(min!=i) {int aux=heap[i];heap[i]=heap[min];heap[min]=aux; 
    
     int aux2=poz2[i];poz2[i]=poz2[min];poz2[min]=aux2;
         poz[poz2[i]]=i;poz[poz2[min]]=min;
    
    minheapify(min);}
            
            }
    
    }
    
    
    
    
void add(int val)
{lheap++;
     heap[lheap]=val;

poz2[lheap]=nrcr;

i=lheap/2;int curent=lheap;
while(i && heap[curent]<heap[i]){int aux=heap[i];heap[i]=heap[curent];heap[curent]=aux; 
         int aux2=poz2[i];poz2[i]=poz2[curent];poz2[curent]=aux2;
         poz[poz2[i]]=i;poz[poz2[curent]]=curent;
         curent=i;i=i/2;}
    
    }
    
void hdelete(int i)
{int nod=poz[i];
heap[nod]=heap[lheap];
poz2[nod]=poz2[lheap];
poz[poz2[nod]]=nod;
int se=nod;
lheap--;
minheapify(se);
int it=nod/2;int curent=nod;
while(it && heap[nod]<heap[it]){int aux=heap[it];heap[it]=heap[nod];heap[nod]=aux; 
         int aux2=poz2[it];poz2[it]=poz2[nod];poz2[nod]=aux2;
         poz[poz2[it]]=it;poz[poz2[nod]]=nod;
         nod=it;it=it/2;}    
     
     }    


int main()
{freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w",stdout);
int m,cerinta;
scanf("%d ",&m);
nrcr=0;
lheap=0;
for(;m;m--)
 {scanf("%d",&cerinta);
   switch(cerinta)
   { case 3 : {
          printf("%d \n", heap[1]); break;}
    case 1 : {scanf("%d",&x); nrcr++;poz[nrcr]=lheap+1;add(x); break; }
    case 2 :{scanf("%d",&x); hdelete(x); break;}
    default : break;}
    

           }
        
       
return 0;
}