Cod sursa(job #797398)

Utilizator andrei_stoicaStoica Andrei Florian andrei_stoica Data 13 octombrie 2012 22:44:44
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include<fstream>
#include<algorithm>
#define N 20000001
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
int heap[N],v[N],poz[N],n;
void schimb(int x,int y)
{
	poz[heap[x]]=y;
	poz[heap[y]]=x;
	swap(heap[x], heap[y]);
}
void up(int x)
{
	while (x>=2 && v[heap[x]]<v[heap[x/2]])
	{
		schimb(x,x/2);
		x/=2;
	}
}
void down(int nod)
{
	int son=nod;
	while (2*nod<=n && son==nod)
	{
		son=2*nod;
		if (son+1<=n && v[heap[son+1]]<v[heap[son]])son++;
		if (v[heap[son]]<v[heap[nod]])
		{
			schimb(nod,son);
			nod=son;
		}
	}
}
int main()
{
	int nr,i,x,l=0,op,aux;
	in>>nr;
	for (i=0; i<nr; i++)
	{
		in>>op;
		if (op==1)
		{
			in>>v[++l];
			heap[++n]=l; 
			poz[l]=n; 
			up(n); 
		}
		if (op==2)
		{
			in>>x;
			aux=poz[x];
			schimb(aux,n); 
			n--;
			down(aux);
		}
		if (op==3)
			out<<v[heap[1]]<<"\n";
	}
}