Cod sursa(job #338900)

Utilizator irene_mFMI Irina Iancu irene_m Data 7 august 2009 13:52:06
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 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)
{
	while(fs(nod)<=L && A[heap[fs(nod)]]<A[heap[nod]] ||
		fd(nod)<=L && A[heap[fd(nod)]]<A[heap[nod]])
		{
			if(fd(nod)<=L)
			{
				if(A[heap[fs(nod)]]<A[heap[fd(nod)]])
				{
					swap(nod,fs(nod));
					poz[heap[nod]]=nod;
					poz[heap[fs(nod)]]=fs(nod);
					nod=fs(nod);
				}
				else
				{
					swap(nod,fd(nod));
					poz[heap[nod]]=nod;
					poz[heap[fd(nod)]]=fd(nod);
					nod=fd(nod);
				}
			}
			else
			{
				swap(nod,fs(nod));
				poz[heap[nod]]=nod;
				poz[heap[fs(nod)]]=fs(nod);
				nod=fs(nod);
			}
		}
}
	

void erase(int nod)
{
	A[nod]=-1;
	urca_heap(poz[nod]);
	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",A[heap[1]]);
	}
	return 0;
}