Cod sursa(job #338885)

Utilizator irene_mFMI Irina Iancu irene_m Data 7 august 2009 12:29:08
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <cstdio>
#include <vector>
#define MaxN 200009
#define fs(x)	(2*(x))
#define fd(x)	(2*(x)+1)

int heap[MaxN],poz[MaxN],A[MaxN],n,x,o,N,L;

void swap(int x,int y)
{
	int aux=heap[x];
	heap[x]=heap[y];
	heap[y]=aux;
}

void urca_heap(int nod)
{
	int tata;
	while(nod>1)
	{
		tata=nod/2;
		if(A[heap[tata]]>A[heap[nod]])
		{
			swap(tata,nod);
			poz[heap[nod]]=nod;
			poz[heap[tata]]=tata;
			nod=tata;
		}
		else
			nod=1;
	}
}
	
void insert(int nod)
{
	N++; L++;
	A[N]=nod;
	heap[L]=N;
	poz[N]=L;
	urca_heap(L);
}

void coboara_heap(int nod)
{
	int fiu;
	for(;;)
	{
		fiu=nod;
		if(fs(nod)<=N && heap[fs(nod)]<heap[fiu])
			fiu=fs(nod);
		if(fd(nod)<=N && heap[fd(nod)]<heap[fiu])
			fiu=fd(nod);
		if(nod>N || fiu==nod)
			return;
		swap(fiu,nod);
		poz[heap[nod]]=nod;
		poz[heap[fiu]]=fiu;
	}
}
	

void erase(int p)
{
	A[p]=-1;
	urca_heap(poz[p]);
	poz[heap[1]]=0;
	heap[1]=heap[L--];
	poz[heap[1]]=1;
	if(L>1)
		coboara_heap(1);
}
	

int main()
{
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&o);
		if(o==1)
		{
			scanf("%d",&x);
			insert(x);
		}
		else
			if(o==2)
			{
				scanf("%d",&x);
				erase(x);
			}
			else
				printf("%d\n",heap[1]);
	}
	return 0;
}