Cod sursa(job #503178)

Utilizator brainwashed20Alexandru Gherghe brainwashed20 Data 21 noiembrie 2010 21:39:13
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include<cstdio>
#include<algorithm>

using namespace std;

#define nmax 200010

int h[nmax], poz[nmax], a[nmax], n, cnt;

void heap_up(int k) {
	while(k>1 && h[k]<h[k/2]) {
		swap(h[k],h[k/2]);
		swap(a[k],a[k/2]);
		poz[a[k]]=k;
		poz[a[k/2]]=k/2;
		k/=2;
	}
}

void heap_down(int k) {
	int son=k;
	if(2*k<=n && h[2*k]<h[son])
		son=2*k;
	if(2*k+1<=n && h[2*k+1]<h[son])
		son=2*k+1;
	if(son!=k) {
		swap(h[k],h[son]);
		swap(a[k],a[son]);
		poz[a[k]]=k;
		poz[a[son]]=son;
		heap_down(son);
	}
}

void insert(int val) {
	n++; cnt++;
	h[n]=val;
	poz[cnt]=n;
	a[n]=cnt;
	heap_up(n);
}

void erase(int k) {
	k=poz[k];
	h[k]=h[n];
	n--;
	if(k>1 && h[k]<h[k/2])
		heap_up(k);
	else
		heap_down(k);
}

int main() {
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	
	int m, val, tip;
	
	scanf("%d",&m);
	while(m--) {
		scanf("%d",&tip);
		switch(tip) {
			case 1:
				scanf("%d",&val);
				insert(val);
				break;
			case 2:
				scanf("%d",&val);
				erase(val);
				break;
			default:
				printf("%d\n",h[1]);
				break;
		}
	}
	
	return 0;
}