Cod sursa(job #712716)

Utilizator gabriel93Robu Gabriel gabriel93 Data 13 martie 2012 18:53:38
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include<stdio.h>
using namespace std;
int n,p;
int heap[200002];
int poz[200002];
int loc[200002];

int tata(int nod)
{
	return nod/2;
}

int fs(int nod)
{
	return nod*2;
}

int fd(int nod)
{
	return nod*2+1;
}

void swap(int &a,int &b)
{
	int aux;
	aux=a;
	a=b;
	b=aux;
}

void sift(int k)
{
	int x;
	do
	{
		x=0;
		if(fs(k) <= n)
			x=fs(k);
		if(fd(k) <=n && heap[fd(k)] < heap[fd(k)])
			x=fd(k);
		if(heap[x] >= heap[k])
			x=0;
		if(x)
		{
			swap(heap[x],heap[k]);
			swap(poz[loc[heap[x]]],poz[loc[heap[k]]]);
			//swap(loc[x],loc[k]);
		}
	}while(x);
}

void perc(int k)
{
	while(k > 1 && heap[tata(k)] > heap[k])
	{
		swap(heap[k],heap[tata(k)]);
		swap(poz[loc[heap[k]]],poz[loc[heap[tata(k)]]]);
		//swap(loc[k],loc[tata(k)]);
		k=tata(k);
	}
}

void add(int k)
{
	n++; p++;
	poz[p]=n;
	loc[k]=p;
	heap[n]=k;
	perc(n);
}

void sterg(int k)
{
	heap[k]=heap[n];
	poz[loc[heap[k]]]=poz[n];
	//loc[k]=loc[n];
	n--;
	if(k>1 && heap[k] < heap[tata(k)])
		perc(k);
	else
		sift(k);
}

int main()
{
	int i,cod,x,k;
	freopen("heapuri.in","r",stdin);
	//freopen("heapuri.out","w",stdout);
	scanf("%d",&k);
	for(i=1;i<=k;i++)
	{
		scanf("%d",&cod);
		if(cod==3)
			printf("%d\n",heap[1]);
		else
		{
			scanf("%d",&x);
			if(cod==1)
				add(x);
			else
				sterg(poz[x]);
		}
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
}