Cod sursa(job #855830)

Utilizator BalcauIonutFMI-Balcau Ionut BalcauIonut Data 15 ianuarie 2013 18:05:14
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include<cstdio>
using namespace std;
#define maxn 200001
int heap[maxn],pos[maxn],hpos[maxn],n,nr;


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;

}

int 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);
	return x;
}

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


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