Cod sursa(job #473268)

Utilizator IrnukIrina Grosu Irnuk Data 28 iulie 2010 15:17:42
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 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,long &svpoz)
{
	if(heap[poz]==x)
	{
		stop=1;
		svpoz=poz;
	}
	else
	{
		if(svpoz==-1 && fiuS(poz)<=heap.size()-1 && heap[poz]<x)
			cauta(x,fiuS(poz),stop,svpoz);
		if(svpoz==-1 && fiuD(poz)<=heap.size()-1 && heap[poz]<x)
			cauta(x,fiuD(poz),stop,svpoz);
	}
}

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,1,0,poz);
	heap[poz]=heap[heap.size()-1];
	heap.pop_back();
	if(poz<=heap.size()-1)
	{
		moveUp(poz);
		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;
			if(x==414)
				k=k;
			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;
}