Cod sursa(job #465967)

Utilizator IrnukIrina Grosu Irnuk Data 25 iunie 2010 16:22:34
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <fstream>
#include <vector>

using namespace std;

vector<long> heap;
fstream fout;

void insereaza(long x)
{
	heap.push_back(x);
	long n=heap.size()-1;


	while(n>0 && heap[n]<heap[n/2])
	{
		long aux=heap[n];
		heap[n]=heap[n/2];
		heap[n/2]=aux;
		n=n/2;
	}

}

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

void cauta(long x,long i,long &p)
{
	if(heap[i]==x)
		p=i;
	else
	{
		if(i*2<heap.size() && heap[i*2]<=x)
			cauta(x,i*2,p);
		if(i*2+1<heap.size() && heap[i*2+1]<=x)
			cauta(x,i*2+1,p);
	}
}

void stergere(long x)
{
	long poz=-1,pozS=-1;
	cauta(x,1,poz);

	heap[poz]=heap[heap.size()-1];
	heap.pop_back();
	long n=heap.size()-1;

	pozS=poz;
	while(pozS>0 && pozS<=n && heap[pozS]<heap[pozS/2])
	{
		long aux=heap[pozS];
		heap[pozS]=heap[pozS/2];
		heap[pozS/2]=aux;
		pozS=pozS/2;
	}

	while(true)
	{
		pozS=-1;

		if(poz*2<=n &&  poz*2+1<=n)
		{
			if(heap[poz*2]<heap[poz*2+1])
				pozS=poz*2;
			else
				pozS=poz*2+1;
		}
		else
			if(poz*2<=n)
				pozS=poz*2;
		
		if(pozS==-1)
			break;
		
		if(heap[pozS]<heap[poz])
		{
			long aux=heap[poz];
			heap[poz]=heap[pozS];
			heap[pozS]=aux;
		}
		poz=pozS;
	}

}

int main()
{
	long k,x;
	int cod;
	fstream fin;
	vector<long> ordine;
	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;

		}
	}
	return 0;
}