Cod sursa(job #1473334)

Utilizator aimrdlAndrei mrdl aimrdl Data 19 august 2015 05:08:28
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <stdio.h>

#define MAX 200005

int h[MAX], added[MAX], loc[MAX], add;
int pos;

inline void swap (int &x, int &y) {
	int temp = x;
	x = y;
	y = temp;
}

int push (int x) {
	int p = pos;
	++pos;
	
	h[p] = x;
	
	int aux = (p-1)/2;
	while (p && h[aux] > h[p]) {
		swap(h[aux], h[p]);
		p = aux;
		aux = (aux - 1) / 2;
	}
	
	return p;
}

void pop (int x) {
	int p = loc[added[x]];
	--pos;
	
	swap(h[p], h[pos]);
	
	int ok = 0;
	
	while (!ok) {
		int aux1 = 2 * p + 1;
		int aux2 = aux1+1;
		
		if (aux2 < pos) {
			int minp = (h[aux1] < h[aux2]) ? aux1 : aux2;
			if (h[minp] < h[p]) {
				loc[h[minp]] = p;
				loc[h[p]] = minp;
				
				swap(h[minp], h[p]);
				p = minp;
			} else {
				ok = 1;
			}
		} else if (aux1 < pos) {
			if (h[aux1] < h[p]) {
				loc[h[aux1]] = p;
				loc[h[p]] = aux1;
				
				swap(h[aux1], h[p]);
				p = aux1;
			} else {
				ok = 1;
			}
		} else {
			ok = 1;
		}
	}
} 

int main(void) {
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	
	int n;
	
	scanf("%d", &n);
	
	for (int i = 0; i < n; ++i) {
		int code;
		scanf("%d", &code);
		
		if (code == 3) {
			printf("%d\n", h[0]);
		} else {
			int x;
			scanf("%d", &x);
			
			if (code == 1) {
				added[pos] = x;
				loc[x] = push(x);
			} else {
				pop(x);
			}
		}
	}
	
	fclose(stdin);
	fclose(stdout);
	
	return 0;
}