Cod sursa(job #1076521)

Utilizator BuseSorinFMI Buse Sorin-Marian BuseSorin Data 10 ianuarie 2014 12:35:44
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <algorithm>
#define Nmax 200100

using namespace std;


int Noduri, N, H[Nmax], v[Nmax], w[Nmax], nr;


void Swap(int x, int y)
{
	swap(w[x], w[y]);
	v[w[x]] = x;
	v[w[y]] = y;
	swap(H[x], H[y]);
}

void Coboara(int nod)
{
	int Son = 0;
	do
	{
		Son = 0;
		// Alege un fiu mai mare ca tatal.
		if (2*nod <= N)
		{
			Son = 2*nod;
			if (2*nod+1 <= N && H[2*nod+1]<H[2*nod]) Son = 2*nod+1;
			if (H[Son] >= H[nod]) Son = 0;
		}
		if (Son)
		{
			Swap(nod, Son);
			nod = Son;
		}
	} while (Son);
}

void Urca(int nod)
{
	int key = H[nod];
	while (nod>1 && key<H[nod/2])
	{
		Swap(nod, nod/2);
		nod = nod/2;
	}
	H[nod] = key;
}


void Sterge(int x)
{
	int nod = v[x];
	Swap(v[x], N);
	--N;
	Urca(nod);
	Coboara(nod);
}

void Adauga(int key)
{
	H[++N] = key;
	v[++nr] = N;
	w[N] = nr;
	Urca(N);
}

int main()
{
	ifstream f("heapuri.in");
	ofstream g("heapuri.out");
	f >> Noduri;
	for (int i = 1; i <= Noduri; ++i)
	{
		int tip;
		f >> tip;
		if (tip == 1)
		{
			int key;
			f >> key;
			Adauga(key);
		}
		else
		if (tip == 2)
		{
			int x;
			f >> x;
			Sterge(x);
		}
		else g << H[1] << '\n'; // min/max din Heap

	}
	f.close(); g.close();
	return 0;
}