Cod sursa(job #473231)

Utilizator IrnukIrina Grosu Irnuk Data 28 iulie 2010 14:19:52
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>
#include <vector>
#define NMAX 200005

using namespace std;

vector<long> ordine,heap;
fstream fin,fout;

long fiuS(long i)
{
	return i<<1;
}
long fiuD(long i)
{
	return (i<<1)+1;
}
void swap(long i, long j)
{
	long aux=heap[i];
	heap[i]=heap[j];
	heap[j]=aux;
}

void moveUp(long poz)
{
	long parinte=poz/2;
	while(heap[parinte]>heap[poz] && parinte>=1)	
	{
		swap(parinte,poz);
		poz=parinte;
		parinte/=2;
	}

}

void insereaza(long x)
{
	heap.push_back(x);
	moveUp(heap.size()-1);
}

void cauta(long x, long &poz,long stop)
{
	if(heap[poz]==x)
	{
		stop=1;
	}
	else
	{
		if(stop==0 && fiuS(poz)<=heap.size()-1)
			cauta(x,(poz=fiuS(poz)),stop);
		if(stop==0 && fiuD(poz)<=heap.size()-1)
			cauta(x,(poz=fiuD(poz)),stop);
	}
}

void moveDown(long poz)
{
	long l,r,pm=-1;
	
	while((l=fiuS(poz))<=heap.size()-1 && pm!=poz)
	{
		pm=poz;
		r=fiuD(poz);
		if(l<=heap.size()-1)
		{
			if(heap[l]<heap[pm])
				pm=l;
			if(r<=heap.size()-1)
				if(heap[r]<heap[pm])
					pm=r;
			if(pm!=poz)
			{
				swap(pm,poz);
				poz=pm;
				pm=-1;
			}
		}
	}
}

void stergere(long x)
{
	long poz=1;
	cauta(x,poz,0);
	heap[poz]=heap[heap.size()-1];
	heap.pop_back();
	moveDown(poz);
}

void minim()
{
	fout<<heap[1]<<'\n';
}

int main()
{
	long k,x;
	int cod;

	ordine.push_back(0);
	fin.open("heapuri.in",ios::in);
	fout.open("heapuri.out",ios::out);
	heap.push_back(0); // punem in heap[0], 0 ca sa incepem de la 1
	fin>>k;

	for(long i=1;i<=k;i++)
	{
		fin>>cod;
		switch(cod)
		{
		case 1:
			fin>>x;
			ordine.push_back(x);
			insereaza(x);
			break;
		case 2:
			fin>>x;
			stergere(ordine[x]);
			break;
		case 3:
			minim();
			break;

		}
	}
	fin.close();
	fout.close();
	return 0;
}