Cod sursa(job #325048)

Utilizator TyberFMI Dogan Adrian Ioan Lucian Tyber Data 18 iunie 2009 17:09:22
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include<stdio.h>
#define nmax 200010
int n,c1,c2,a[nmax],heap[nmax],pos[nmax];
void push(int);
void del(int);
int main()
{
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	int i,x,t;
	scanf("%d",&n);
	for(i=1;i<=n;i++)
	{
		scanf("%d",&t);
		if(t<3)
			scanf("%d",&x);
		if(t==1)
		{
			c1++;
			c2++;
			a[c2]=x;
			heap[c1]=c2;
			pos[c2]=c1;
			push(c1);
		}
		if(t==2)
		{
			a[x]=-1;
			if(pos[x]!=0&&1<=x&&x<=c2)
			{
				push(pos[x]);
				pos[heap[1]]=0;
				heap[1]=heap[c1--];
				pos[heap[1]]=1;
				if(c1>1) 
					del(1);
			}
		}
		if(t==3)printf("%d\n",a[heap[1]]);
	}
	return 0;
}
void push(int x)
{
	int q;
	while(x/2&&a[heap[x]]<a[heap[x/2]])
	{
		q=heap[x];
		heap[x]=heap[x/2];
		heap[x/2]=q;
		pos[heap[x]]=x;
		pos[heap[x/2]]=x/2;
		x=x/2;
	}
}
void del(int x)
{
	int q,y=0;
	while(x!=y)
	{
		y=x;
		if(y*2<=c1&&a[heap[x]]>a[heap[y*2]])x=y*2;
		if(y*2+1<=c1&&a[heap[x]]>a[heap[y*2+1]])x=y*2+1;
		q=heap[x];
		heap[x]=heap[y];
		heap[y]=q;
		pos[heap[x]]=x;
		pos[heap[y]]=y;
	}
}