Cod sursa(job #1473343)

Utilizator aimrdlAndrei mrdl aimrdl Data 19 august 2015 05:40:20
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <stdio.h>

#define MAX 200005

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

inline void swap (int x, int y) {
	loc[h[x]] = y;
	loc[h[y]] = x;
	
	int temp = h[x];
	h[x] = h[y];
	h[y] = temp;
}

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

void pop (int x) {
	int p = loc[added[x]];
	--pos;
	
	swap(p, pos);
	
	int ok = 0;
	
	while (!ok) {
		int minp;
		if (2*p+1 >= pos) {
			ok = 1;
		} else {
			if (2*p+2 < pos) {		
				minp = (h[2*p+2] < h[2*p+1]) ? (2*p+2) : (2*p+1);
			} else {
			minp = 2*p+1;
			}
			
			if (h[minp] < h[p]) {
				swap(minp, p);
			} 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-1);
			}
		}
	/*
		printf("test: ");
		for (int i = 0; i < pos; ++i) {
			printf("%d ", h[i]);
		}
		printf("\n");
		*/
	}
	
	fclose(stdin);
	fclose(stdout);
	
	return 0;
}