Cod sursa(job #650090)

Utilizator ms-ninjacristescu liviu ms-ninja Data 17 decembrie 2011 12:56:38
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
using namespace std;
#define dim 200001
#define inf 0x3f3f3f3f
int v[dim],val,coada[dim],contor=1,poz[dim];

inline int father(int nod){
	return nod/2;
}
inline int st_son(int nod){
	return nod*2;
}
inline int dr_son(int nod){
	return nod*2+1;
}


void sift(int n, int x){
	int son;
	do
	{
		son=0;
		if(st_son(x)<=n){
			son=st_son(x);
			if(dr_son(x)<=n && v[dr_son(x)]<v[st_son(x)])
				son=dr_son(x);
			if(v[son]>=v[x])
				son=0;
		}
		
		if(son)
		{
			swap(v[x],v[son]);
			x=son;
		}
	}while(son);
}


void percolate(int n, int k){
	int key=v[k];
	while(k>1 && key<v[father(k)])
	{
		v[k]=v[father(k)];
		k=father(k);
	}
	v[k]=key;
}

void insert(int n, int key){
	v[contor]=key;
	percolate(n,n);
}

void cut(int& n, int k){
	v[k]=v[n];
	--n;
	
	if(k>1 && v[k]<v[father(k)])
		percolate(n,k);
	else
		sift(n,k);
}

int main()
{
	ifstream fin("heapuri.in");
	ofstream fout("heapuri.out");
	int n, i,x;
	
	fin>>n;
	fin>>x >>v[1];
	coada[1]=v[1];
	poz[1]=v[1];
	for(i=2;i<=n;++i)
	{
		int tip=0;
		fin>>tip;
		if(tip==1)
		{
		++contor;
		fin>>x;
		coada[contor]=x;
		//poz[contor]=x;
		insert(contor,x);
		}
		else
			if(tip==2)
			{
				int query,raspuns,ok=0;
				fin>>query;
				raspuns=coada[query];
				
				for(int j=1;;++j)
					if(v[j]==raspuns)
					{
						cut(contor,j);
						break;
					}
			}
			else
				fout<<v[1]<<'\n';
	}
	
	return 0;
}