Cod sursa(job #1047204)

Utilizator buzu.tudor67Tudor Buzu buzu.tudor67 Data 4 decembrie 2013 00:29:56
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include<fstream>
#include<algorithm>
using namespace std;
ifstream fi("heapuri.in");
ofstream fo("heapuri.out");

int poz[200001],ordine[200001],k=0,n=0;
int i,t,x,h[200001];
short int oper;

void downheap(int n,int k){
     int son=1;
     
     while(son)
      {
       son=0;
       
       if(2*k<=n) {
                   son=2*k;
                   if(2*k+1<=n && h[2*k+1]<h[2*k])
                   son=2*k+1;
                   if (h[son]>=h[k]) son=0;
                  }
       if(son) {
                swap(h[k],h[son]);
                swap(ordine[k],ordine[son]);
                
                poz[ordine[k]]=k;
                poz[ordine[son]]=son;
                
                k=son;
               }
      }
}

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

void insertheap(int &n,int x){
     h[++n]=x;
     ordine[n]=++k;// ordinea pe care o ocupa nodul n in vectorul initial
     poz[k]=n; // pozitia elementului k in heap
     upheap(n,x);
}

void deleteheap(int &n,int k){
     h[k]=h[n];
     ordine[k]=ordine[n];
     poz[ordine[k]]=k;
     n--;

     if(h[k]<h[k/2]) upheap(n,k);
     else downheap(n,k);
}

int main(){
    fi>>t;
    
    for(i=1;i<=t;i++){
                      fi>>oper;
                      if(oper==3) fo<<h[1]<<"\n";
                      else {
                            fi>>x;
                            if(oper==1) insertheap(n,x);
                            else deleteheap(n,poz[x]);
                           }
                     }
    
    fi.close();
    fo.close();
    return 0;
}