Cod sursa(job #793906)

Utilizator andrei_stoicaStoica Andrei Florian andrei_stoica Data 4 octombrie 2012 17:54:41
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include<fstream>
#include<algorithm>
#define N 200010
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
int heap[N],v[N],poz[N];
void down(int n, int nod)
{
    int son;
    do
	{
        son=0;
        if(nod*2<=n)
		{
            son=nod*2;
            if (nod*2+1<=n && heap[nod*2+1]<heap[nod*2])son=nod*2+1;
            if (heap[son]>=heap[nod])son=0;
        }
        if(son)
		{
            swap(heap[nod], heap[son]);
			poz[heap[son]]=son;
			poz[heap[nod]]=nod;
            nod=son;
        }
    } while (son);
}
void up(int n, int nod) {
    int key=heap[nod];
    while (nod>1 && key<heap[nod/2]) {
        heap[nod]=heap[nod/2];
		poz[heap[nod]]=nod;
        nod/=2;
    }
    heap[nod]=key;
	poz[key]=nod;
}
int main()
{
	int nr,i,elem,n=0,x;
	short op;
	in>>nr;
	for(i=0;i<nr;i++)
	{
		in>>op;
		if(op!=3)in>>elem;
		else out<<heap[1]<<"\n";
		if(op==1)
		{
			heap[++n]=elem;
			poz[heap[n]]=n;
			v[n]=elem;
			up(n,n);
		}
		if(op==2)
		{
			x=poz[v[elem]];
			heap[x]=heap[n];
			--n;
			if (x>1 && heap[x]>heap[x/2]) up(n, x);
			else down(n, x);
		}
	}
}