Cod sursa(job #1217892)

Utilizator andreey_047Andrei Maxim andreey_047 Data 8 august 2014 16:39:06
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <cstdio>
#include <algorithm>
#define nmax 200001
using namespace std;
typedef int Heap;
Heap H[nmax];
int n,m,poz[nmax],f[3000000];
int father(int k){return k/2;}
int leftson(int k){return 2*k;}
int rightson(int k){return 2*k+1;}

void sift(int k){
    int son;
  do{
        son = 0;
 if(leftson(k) <= m){
    son = leftson(k);
    if(rightson(k) <= m && H[rightson(k)] < H[leftson(k)])
        son = rightson(k);
    if(H[k] <= H[son]) son = 0;
    }
    if(son){
        swap(f[H[k]],f[H[son]]);
        swap(H[k],H[son]);
        k = son;
    }
 }while(son);
}
void percolate(int k){
 while(k > 1 && H[father(k)] > H[k])
    {
        swap(f[H[k]],f[H[father(k)]]);
       swap(H[k],H[father(k)]);
        k = father(k);
     }
}
void Adauga(int k){
 H[++m] = k;
 f[k] = m;
 percolate(m);
}
void Taie(int k){
int key;
 f[H[m]] = f[poz[k]];
 swap(H[f[poz[k]]],H[m]);
 m--;
 if(H[f[k]] <= H[father(k)] || f[k] == 1) percolate(f[k]);
 else sift(f[k]);
}
int main(){
    int i,j,cod,x,nr=0;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
   while(n--){
      scanf("%d",&cod);
      if(cod == 3){printf("%d\n",H[1]);
      }
      else if(cod < 3){
        scanf("%d",&x);
         if(cod == 1) {nr++;poz[nr]=x;Adauga(x);}
         else {
            Taie(x);
}
      }
   }
    return 0;
}