Cod sursa(job #313640)

Utilizator Alexa_ioana_14Antoche Ioana Alexandra Alexa_ioana_14 Data 9 mai 2009 15:09:23
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include<stdio.h>
#define N 200005
int n;
struct heap{int v,p;}h[N];
void percolate(int k)
{
	int key=h[k].v;
	while (k>1 && key<h[k/2].v)
	{
		h[k]=h[k/2];
		k/=2;
	}
	h[k].v=key;
}
void insert(int x)
{
	h[++n].v=x;
	h[n].p=n;
	percolate(n);
}
void shift(int k)
{
	int f;
	do {
		f=0;
		if(2*k<=n)
		{
			f=2*k;
			if (2*k+1<=n && h[2*k].v>h[2*k+1].v)
				f=2*k+1;
			if (h[f].v>=h[k].v)
				f=0;
			if (f)
			{
				heap aux=h[f];
				h[f]=h[k];
				h[k]=aux;
				k=f;
			}
		}
	}
	while (f);
}
void del (int k)
{
	h[k]=h[n];
	--n;
	if (k>1 && h[k].v<h[k/2].v)
		percolate(k);
	else
		shift(k);
}
void citire()
{
	freopen("heap.in","r",stdin);
	freopen("heap.out","w",stdout);
	int m;
	scanf("%d",&m);
	while (m)
	{
		int x;
		scanf("%d",&x);
		if (x==1)
		{
			scanf("%d",&x);
			insert(x);
		}
		if (x==2)
		{
			scanf("%d",&x);
			del(x);
		}
		if (x==3)
			printf("%d",h[1]);
		--m;
	}
}
int main()
{
	citire();
	return 0;
}