Cod sursa(job #331543)

Utilizator ciprianfFarcasanu Alexandru Ciprian ciprianf Data 14 iulie 2009 13:40:18
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <stdio.h>
#define N 200005
int n,m,h[N],poz[N],v[N];
void swap(int &x,int &y){
	int z=x;x=y;y=z;
}
void sift(int k){
	int son;
	do{
		son=0;
		if(2*k<=n) son=2*k;
		if(2*k+1<=n && h[2*k+1]<h[son]) son=2*k+1;
		if(son && h[son]<h[k]){
			poz[h[son]]=k;
			poz[h[k]]=son;
			swap(h[k],h[son]);
			k=son;
		}
		else son=0;
	}
	while(son);
}
void percolate(int k){
	while(k>1 && h[k/2]>h[k]){
		poz[h[k]]=k/2;
		poz[h[k/2]]=k;
		swap(h[k],h[k/2]);
		k/=2;
	}
}
void add(int x){
	h[++n]=x;
	poz[x]=n;
	percolate(n);
}
void cut(int x){
	poz[h[n]]=x;
	swap(h[n],h[x]);
	n--;
	if(h[x]<h[x/2]) percolate(x);
	else sift(x);
}
int main(){
	int i,x,y;
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	scanf("%d",&m);
	for(i=1;i<=m;i++){
		scanf("%d",&x);
		if(x!=3){
			scanf("%d",&y);
			if(x==1) v[++v[0]]=y,add(y);
			else 
				cut(poz[v[y]]);
		}
		else printf("%d\n",h[1]);
	}
	return 0;
}