Cod sursa(job #362183)

Utilizator bigdoggMic Matei bigdogg Data 8 noiembrie 2009 13:05:31
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream.h>

struct heap{ int x,v; };

int n=0,v[200000];
heap h[200000];

int up(int k);
int down(int k);

int main()
{
	int i,j,op,op_n;
	
	ifstream in("heapuri.in");
	ofstream out("heapuri.out");
	in>>op_n;
	for(i=1;i<=op_n;++i)
	{
		in>>op;
		switch(op)
		{
			case 1:
				in>>h[++n].x;	h[n].v=n;
				v[n]=up(n); 
				break;
			case 2:
				in>>j;
				h[v[j]]=h[n]; v[h[n].v]=v[j]; --n; 
				if(v[j]>1 && h[v[j]].x<h[v[j]/2].x) v[v[j]]=up(v[j]);
				else v[v[j]]=down(v[j]);
				break;
			case 3: out<<h[1].x<<'\n'; break;
		}
	}
	out.close();

	return 0;
}

int up(int k)
{
	int father=k/2;
	heap key=h[k];
	
	while(k>1 && key.x<h[father].x)
	{
		h[k]=h[father];
		v[h[father].v]=k;
		k=father; father=k/2;
	}
	h[k]=key;
	
	return k;
}

int down(int k)
{
	int son,left,right;
	heap key=h[k];
	
	do
	{
		son=0; left=k*2;
		if(left<=n)
		{
			son=left; right=left+1;
			if(right<=n && h[right].x<h[left].x) son=right;
			if(h[son].x<key.x){ h[k]=h[son]; v[h[son].v]=k; k=son; }
			else son=0;
		}
	}while(son);
	h[k]=key;
	
	return k;
}