Cod sursa(job #795579)

Utilizator radustn92Radu Stancu radustn92 Data 8 octombrie 2012 23:29:51
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <stdio.h>
#define NMAX 200005
int n,A[NMAX],m,heap[NMAX],r,poz[NMAX];
void schimba(int x,int y)
{
	poz[heap[x]]=y; poz[heap[y]]=x;
	int aux=heap[x]; 
	heap[x]=heap[y]; heap[y]=aux;
}
void up(int x)
{
	while (x/2>=1 && A[heap[x]]<A[heap[x/2]])
	{
		schimba(x,x/2);
		x/=2;
	}
}
void down(int x)
{
	if (2*x<=r || 2*x+1<=r)
	{
		int best=2*x;
		if (2*x+1<=r && A[heap[2*x+1]]<A[heap[best]])
			best=2*x+1;
		if (A[heap[best]]<A[heap[x]])
		{
			schimba(x,best);
			down(best);
		}
	}
}
int main()
{
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	int i,tip,x,y;
	scanf("%d",&n);
	for (i=1; i<=n; i++)
	{
		scanf("%d",&tip);
		if (tip==1)
		{
			scanf("%d",&A[++m]);
			heap[++r]=m; poz[m]=r; 
			up(r); 
		}
		if (tip==2)
		{
			scanf("%d",&x);
			y=poz[x];
			schimba(y,r); r--;
			down(y);
		}
		if (tip==3)
			printf("%d\n",A[heap[1]]);
	}
	return 0;
}