Cod sursa(job #634921)

Utilizator sebii_cSebastian Claici sebii_c Data 17 noiembrie 2011 22:26:45
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <stdio.h>

#define NMAX 200010

int N, L, NR;
int A[NMAX], heap[NMAX], pos[NMAX];

void push(int x)
{
	int aux;
	
	while (x >> 1 && A[heap[x]] < A[heap[x>>1]]) {
		aux = heap[x];
		heap[x] = heap[x>>1];
		heap[x>>1] = aux;
		
		pos[heap[x]] = x;
		pos[heap[x>>1]] = x>>1;
		x >>= 1;
	}
}

void pop(int x)
{
	int aux, y = 0;
	
	while (x != y) {
		y = x;
		
		if (y << 1 <= L && A[heap[x]]>A[heap[(y<<1)]]) 
			x = y<<1;
		if ((y<<1) + 1 <= L && A[heap[x]] > A[heap[(y<<1) + 1]]) 
			x = (y<<1) + 1;
		
		aux = heap[x];
		heap[x] = heap[y];
		heap[y] = aux;
	
		pos[heap[x]] = x;
		pos[heap[y]] = y;
	}
}

int main()
{
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	
	int i, x, n, code;
	scanf("%d", &n);
	
	for (i=1; i<=n; ++i) {
		scanf("%d", &code);
		if (code == 1) {
			scanf("%d", &x);
			++L; ++NR;
			A[NR] = x;
			heap[L] = NR;
			pos[NR] = L;
	
			push(L);
		}
		if (code == 2) {
			scanf("%d", &x);
			A[x] = -1;
			push(pos[x]);
			pos[heap[1]] = 0;
			heap[1] = heap[L--];
			pos[heap[1]] = 1;
			if (L > 1)
				pop(1);
		}
	
		if (code == 3)
			printf("%d\n", A[heap[1]]);
	}
	return 0;
}