Cod sursa(job #403301)

Utilizator antoanelaAntoanela Siminiuc antoanela Data 24 februarie 2010 20:17:41
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <cstdio>
#define nmax 200010

int h[nmax], a[nmax], poz[nmax], N, l, nr;

void swap(int a, int b)
{
	int c=h[a];
	h[a]=h[b];
	h[b]=c;
	poz[h[a]]=a;
	poz[h[b]]=b;
}

void heap_up(int nod)
{
	if (nod>1)
		if (a[h[nod/2]]>a[h[nod]])
		{
			swap(nod, nod/2);
			heap_up(nod/2);
		}
}

void heap_down(int nod)
{
	if (nod*2<=l)
	{
		int c=2*nod;
		if (a[h[c]]>a[h[c+1]] && nod*2+1<=l) c++;
		if (a[h[nod]]>a[h[c]])
		{
			swap(nod, c);
			heap_down(c);
		}
	}
}

int main()
{
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	scanf("%d",&N);
	int i, t, x, j;
	for (i=1; i<=N; i++)
	{
		scanf("%d",&t);
		if (t==1)
		{
			scanf("%d",&x);
			l++; nr++;
			h[l]=nr;
			a[nr]=x;
			poz[nr]=l;
			heap_up(l);
		} else
		if (t==2)
		{
			scanf("%d",&x);
			h[poz[x]]=h[l];
			poz[h[l]]=poz[x];
			l--;
			heap_down(1);
		} else printf("%d\n",a[h[1]]);
	}
}