Cod sursa(job #427468)

Utilizator mihai995mihai995 mihai995 Data 27 martie 2010 21:26:48
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
using namespace std;
int heap[1<<18],v[1<<18],poz[1<<18],n;

void exchange(int a,int b)
{
	int aux;
	aux=heap[a];
	heap[a]=heap[b];
	heap[b]=aux;
	aux=v[a];
	v[a]=v[b];
	v[b]=aux;
	aux=poz[v[a]];
	poz[v[a]]=poz[v[b]];
	poz[v[b]]=aux;
}

void undo(int x)
{
	int p=x/2;
	if (heap[p]>heap[x])
	{
		exchange(x,p);
		if (p>1)
			undo(p);
	}
}

void redo(int x)
{
	int l=2*x,r=l+1,m=x;
	if (heap[l]<heap[m] && l<=n)
		m=l;
	if (heap[r]<heap[m] && r<=n)
		m=r;
	if (m!=x)
	{
		exchange(m,x);
		redo(m);
	}
}

void add(int x,int i)
{
	heap[++n]=x;
	v[n]=i;
	poz[i]=n;
	undo(n);
}

void remove(int x)
{
	exchange(x,n--);
	redo(x);
}

int main()
{
	int i=0,nr,x;
	ifstream in("heapuri.in");
	ofstream out("heapuri.out");
	in>>nr;
	while (nr--)
	{
		in>>x;
		switch(x)
		{
			case 1:in>>x;add(x,++i);break;
			case 2:in>>x;remove(poz[x]);break;
			case 3:out<<heap[1]<<"\n";break;
		}
	}
	return 0;
}