Cod sursa(job #473387)

Utilizator IrnukIrina Grosu Irnuk Data 29 iulie 2010 12:09:48
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <fstream>
#include <vector>
#define NMAX 200005

using namespace std;

long pozitia[NMAX];
vector<long> ordine;
struct nod
{
	long el,pos;
	nod(){}
	nod(long nel,long npos) : el(nel),pos(npos){}
};
vector<nod> 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)
{
	nod aux;
	long aux1;
	aux1=pozitia[heap[i].pos];
	pozitia[heap[i].pos]=pozitia[heap[j].pos];
	pozitia[heap[j].pos]=aux1;

	aux=heap[i];
	heap[i]=heap[j];
	heap[j]=aux;
}

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

}

void insereaza(nod x)
{
	heap.push_back(x);
	pozitia[x.pos]=heap.size()-1;
	moveUp(heap.size()-1);
}




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].el<heap[pm].el)
				pm=l;
			if(r<=heap.size()-1)
				if(heap[r].el<heap[pm].el)
					pm=r;
			if(pm!=poz)
			{
				swap(pm,poz);
				poz=pm;
				pm=-1;
			}
		}
	}
}

void stergere(long x)
{
	long poz=-1;
	/*cauta(x,1,poz);*/
	//poz=cauta2(x);
	poz=pozitia[x];
	pozitia[x]=0;
	pozitia[heap[heap.size()-1].pos]=poz;
	heap[poz]=heap[heap.size()-1];
	heap.pop_back();
	if(poz<=heap.size()-1)
	{
		moveUp(poz);
		moveDown(poz);
	}
}

void minim()
{
	fout<<heap[1].el<<'\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(nod(0,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(nod(x,ordine.size()-1));
			break;
		case 2:
			fin>>x;
			stergere(x);
			break;
		case 3:
			minim();
			break;

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