Cod sursa(job #401737)

Utilizator laserbeamBalan Catalin laserbeam Data 23 februarie 2010 08:31:18
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include<cstdlib>
#include<cstdio>
using namespace std;

#define NMAX 200002
int a[NMAX], heap[NMAX], poz[NMAX];
int n,m;

void upheap(int p)
{
	int q = p>>1;
	int aux;
	while (q && a[heap[p]] < a[heap[q]])
	{
		aux 	= heap[p];
		heap[p]	= heap[q];
		heap[q] = aux;
		
		poz[heap[p]] = p;
		poz[heap[q]] = q;
		p = q;
		q = p>>1;
	}
}

void downheap(int p)
{
	int aux, q = 0;
	while (p != q)
	{
		q = p;
		if ( (q<<1)   <= m && a[heap[p]] > a[heap[q<<1]]    ) p = q<<1;
		if ( (q<<1)+1 <= m && a[heap[p]] > a[heap[(q<<1)+1]]) p = (q<<1)+1;
		
		aux		= heap[p];
		heap[p] = heap[q];
		heap[q] = aux;
		
		poz[heap[p]] = p;
		poz[heap[q]] = q;
	}
}

int main()
{
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	int tests,type,x;
	scanf("%d ", &tests);
	for ( ; tests; --tests)
	{
		scanf("%d ", &type);
		if (type < 3) scanf("%d ", &x);
		if (type == 1)
		{
			++n; ++m;
			a[n]	= x;
			heap[m] = n;
			poz[n]	= m;
			upheap(m);
		} else if (type == 2) {
			a[x]			= -1;
			upheap(poz[x]);
			poz[heap[1]] 	= 0;
			heap[1]			= heap[m--];
			poz[heap[1]]	= 1;
			downheap(1);
		} else if (type == 3)
		{
			for (int i = 1; i <= m; ++i) fprintf(stderr, "%d ", a[heap[i]]);
			fprintf(stderr, "\n");
			printf("%d\n", a[heap[1]]);
		}
	}
	
	return EXIT_SUCCESS;
}