Cod sursa(job #1217921)

Utilizator andreey_047Andrei Maxim andreey_047 Data 8 august 2014 19:16:12
Problema Heapuri Scor 100
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,f[nmax],g[nmax],nr,M;
int father(int k){return k/2;}
int leftson(int k){return 2*k;}
int rightson(int k){return 2*k+1;}
void Swap(int x , int y){
        swap(f[g[x]],f[g[y]]);
        swap(g[x],g[y]);
        swap(H[x],H[y]);
}
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(k,son);
        k = son;
    }
 }while(son);
}
void percolate(int k){
 while(k > 1 && H[father(k)] > H[k])
    {
        Swap(k,father(k));
        k = father(k);
     }
}
void Adauga(int k){
 H[++m] = k;
 M++;
 f[M] = m ;
 g[m] = M;
 percolate(m);
}
void Taie(int k)
{
    int q = f[k];
	Swap(q, m);
	m--;
	if (q > 1 && H[q] < H[father(q)])
		percolate(q);
	else
		sift(q);
}
int main(){
    int i,j,cod,x;
    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) Adauga(x);
         else {
            Taie(x);
}
      }
   }
    return 0;
}