Cod sursa(job #357804)

Utilizator tranbachhaiTran Bach Hai tranbachhai Data 20 octombrie 2009 19:34:38
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include<stdio.h>
long n,nr,h[200010],v[200010];
void coboara(long temp)
{
long aux,nm=nr/2,fiu1,fiu2;
while(temp<=nm)
{
	fiu1=temp*2;
	fiu2=temp*2+1;
	if (v[temp]>v[fiu1] || v[temp]>v[fiu2] )
	{
		if(fiu1==nr)
		{
			if (v[fiu1]<v[temp])
				{
				aux=v[fiu1];
				v[fiu1]=v[temp];
				v[temp]=aux;
				aux=h[fiu1];
				h[fiu1]=h[temp];
				h[temp]=aux;
				temp=fiu1;
				}
			else break;
			}
		else if(v[fiu2]<=v[fiu1])
		{
				aux=v[fiu2];
				v[fiu2]=v[temp];
				v[temp]=aux;
				aux=h[fiu2];
				h[fiu2]=h[temp];
				h[temp]=aux;
				temp=fiu2;
		}
		else 
		{
				aux=v[fiu1];
				v[fiu1]=v[temp];
				v[temp]=aux;
				aux=h[fiu1];
				h[fiu1]=h[temp];
				h[temp]=aux;
				temp=fiu1;
		}
	}
	else break;
}
}
void urca(long temp)
{
long aux,tata;
while(temp>=2&& nr>2)
{
tata=temp/2;
if (v[temp]<v[tata])
{
	aux=v[temp];
	v[temp]=v[tata];
	v[tata]=aux;
	aux=h[temp];
	h[temp]=h[tata];
	h[tata]=aux;
	temp=tata;
}
else break;
}
coboara(temp);
}
int main()
{
long temp,i,na,x=0;
freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w",stdout);
scanf("%ld",&n);
 for (i=1;i<=n;++i)
{
	scanf("%ld",&temp);
	if (temp==1)
	{
			scanf("%ld",&temp);
			v[++nr]=temp;
			h[nr]=++x;
			urca(nr);
	}
	else if (temp==2)
	{
			scanf("%ld",&temp);
			na=nr+1;
			while(h[--na]!=temp);
			v[na]=v[nr];
			h[na]=h[nr];
			--nr;
			urca(na);
	}
	else
		
	{
		printf("%ld\n",v[1]);
	}
}
return 0;
}