Cod sursa(job #495259)

Utilizator PlayLikeNeverB4George Marcus PlayLikeNeverB4 Data 24 octombrie 2010 16:43:22
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <stdio.h>

const int maxn=200001;
int v[maxn],H[maxn],poz[maxn],hp,N,M;


void swap(int *a, int *b)
{
	int aux;
	aux=*a;
	*a=*b;
	*b=aux;
}
void upheap(int k)
{
	while(k && v[H[k]]<v[H[k/2]])
	{
		swap(&poz[H[k]],&poz[H[k/2]]);
		swap(&H[k],&H[k/2]);
		k/=2;
	}
}
void downheap(int k)
{
	int son;
	do
	{
		son=0;
		if(2*k<=hp)
		{
			son=2*k;
			if(2*k+1<=hp && v[H[son]]>v[H[2*k+1]])
				son=2*k+1;
			if(v[H[son]]>=v[H[k]]) son=0;
		}
		if(son)
		{
			swap(&poz[H[son]],&poz[H[k]]);
			swap(&H[son],&H[k]);
			k=son;
		}
	}
	while(son);
}

void insert(int x)
{
	hp++; N++;
	v[N]=x;
	H[hp]=N;
	poz[N]=hp;
	upheap(hp);
}

void del(int k)
{
	poz[H[k]]=poz[H[hp]];
	swap(&H[k],&H[hp]);
	hp--;
	if(k>1 && v[H[k]]<v[H[k/2]]) upheap(k);
		else downheap(k);
}
int main()
{
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	scanf("%d",&M);
	N=0; hp=0;
	for(int j=1;j<=M;j++)
	{
		int x,y;
		scanf("%d",&x);
		if(x<3)
		{
			scanf("%d",&y);
			if(x==1) insert(y);
				  else del(poz[y]);
		}
		else printf("%d\n",v[H[1]]);
	}
}