Cod sursa(job #239030)

Utilizator ilincaSorescu Ilinca ilinca Data 3 ianuarie 2009 22:04:16
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <stdio.h>
#include <vector>

int n, nr_h, nr_i, h [200005], a [200005], p [200005];


void up (int k)
{
	int aux;
	while (k > 1 && a [h [k]] < a [h [k>>1]]) 
	{
		aux=h [k];
		h [k]=h [k>>1];
		h [k>>1]=aux;
		aux=p [h [k]];
		p [h [k]]=p [h [k>>1]];
		p [h [k>>1]]=aux;
		k>>=1;
	}
}

void down (int k)
{
	int f, aux;
	do
	{
		if (k<<1 <= nr_h)
		{
			f=k<<1;
			if (f+1 <= nr_h && a [h [(k<<1)|1]] < a [h [f]])
				f|=1;
			if (a [h [k]] > a [h [f]])
			{
				aux=p [h [k]];
				p [h [k]]=p [h [f]];
				p [h [f]]=aux;
				aux=h [k];
				h [k]=h [f];
				h [f]=aux;
			}
			else 
				f=0;	
		}
		else
			f=0;
	} while (f);
}

int main ()
{
	freopen ("heapuri.in", "r", stdin);
	freopen ("heapuri.out", "w", stdout);
	int i, tip, x;
	scanf ("%d", &n);
	for (i=1; i<=n; ++i)
	{
		scanf ("%d", &tip);
		if (tip == 3)
			printf ("%d\n", a [h [1]]);
		else
		{
			scanf ("%d", &x);
			if (tip == 1)
			{
				++nr_h; ++nr_i;
				h [nr_h]=nr_i;
				a [nr_i]=x;
				p [nr_i]=nr_h;
				up (nr_h);
			}
			else
			{
				a [x]=-1;
				h [p [x]]=h [nr_h];
				--nr_h;
				if (p [x] > 1 && a [h [p [x]]] <= a [h [p [x]>>1]])
					up (p [x]);
				else 
					down (p [x]);
				p [x]=-1;
			}
		}
	}
	return 0;
}