Cod sursa(job #855819)

Utilizator BalcauIonutFMI-Balcau Ionut BalcauIonut Data 15 ianuarie 2013 17:52:06
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include<cstdio>
using namespace std;
#define maxn 200001
int heap[maxn],pos[maxn],hpos[maxn],n;


void swaph(int x,int y){
	int aux;
	aux=heap[y];
	heap[y]=heap[x];
	heap[x]=aux;

	aux=hpos[y];
	hpos[y]=hpos[x];
	hpos[x]=aux;

	pos[hpos[x]]=x;
	pos[hpos[y]]=y;
}

int urca(int x){
	
	while(x>1 && heap[x/2]>heap[x]){
		swaph(x,x/2);
		x/=2;
	}
	return x;

}

void coboara(int x){
	int l,r,f;
	do{
	f=0;
	l=2*x,r=2*x+1;
	if(l<=n && heap[l]<heap[x])
		f=l;
	if(r<=n && heap[r]<heap[x]){
		if(f){
			if(heap[r]<heap[f])
				f=r;
		}else f=r;
	}
	if(f){
		swaph(f,x);
		x=f;
	}
	}while(f);

}

void sterge(int x){
	swaph(x,n);
	--n;
	x=urca(x);
	coboara(x);
}


int main(){
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	int m; scanf("%d",&m);
	n=0; int cod,x;
	while(m>0){
		--m;
		scanf("%d",&cod);
		switch(cod){
			case 1:{
			scanf("%d",&x);
			heap[++n]=x;
			pos[n]=n;
			hpos[n]=n;
			urca(n);
			break;
			}
			case 2:{
			scanf("%d",&x);
			x=pos[x];
			sterge(x);
			break;
			}
			case 3:{
				printf("%d\n",heap[1]);
			}
		}
	}
}