Cod sursa(job #313714)

Utilizator Alexa_ioana_14Antoche Ioana Alexandra Alexa_ioana_14 Data 9 mai 2009 16:51:26
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include<stdio.h>
#define N 200005
int n,h[N],p[N],v[N],nh;
void urc(int k)
{
	int y=h[k];
	while (k>1 && v[y]<v[h[k/2]])
	{
		h[k]=h[k/2];
		p[h[k]]=k;
		k/=2;
	}
	h[k]=y;
	p[y]=k;
}
void insert(int n)
{
	h[++nh]=n;
	p[n]=nh;
	urc(nh);
}
void cobor(int k)
{
	int f,aux;
	/*
	do
	{
		f=0;
		if (2*k<=nh)
		{
			f=2*k;
			if (2*k+1<=nh && v[h[2*k+1]]<v[h[2*k]])
				f=2*k+1;
			if (v[h[f]]>v[h[k]])
				f=0;
			if (f)
			{
				int aux=v[h[f]];
				v[h[f]]=v[h[k]];
				h[k]=aux;
				aux=p[k];
				p[k]=p[f];
				p[f]=aux;
				k=f;
			}
		}
	}
	while (f);
	*/
	while(true)
	{
		f=k;
		if(2*k<=nh && v[h[2*k]]<v[h[f]])
			f=2*k;
		if(2*k+1<=nh && v[h[2*k+1]]<v[h[f]])
			f=2*k+1;
		if(f==k)
			return;
		aux=h[k];
		h[k]=h[f];
		h[f]=aux;
		p[h[k]]=k;
		p[h[f]]=f;
		k=f;
	}
}
void del (int k)
{
	h[p[k]]=h[nh];
	p[h[p[k]]]=p[k];
	--nh;
	if (p[k]>1 && v[h[p[k]]]<v[h[p[k]/2]])
		urc(p[k]);
	else 
		cobor(p[k]);
}
void citire()
{
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	int m,x,tip;
	scanf("%d",&m);
	while (m)
	{
		scanf("%d",&tip);
		if (tip==1)
		{
			scanf("%d",&v[++n]);
			insert(n);
		}
		if (tip==2)
		{
			scanf("%d",&x);
			del(x);
		}
		if (tip==3)
			printf("%d\n",v[h[1]]);
		--m;
	}
}
int main()
{
	citire();
	return 0;
}