Cod sursa(job #2742453)

Utilizator SteFUNGrigorescu Stefan Dumitru SteFUN Data 20 aprilie 2021 22:54:19
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
// Heapuri

#include <iostream>
#include <fstream>

std::ifstream f("heapuri.in");
std::ofstream g("heapuri.out");

typedef short int shint;

struct nod
{
	int val;
	int poz_in_ordcrono;

	void refresh(nod hp[], int valoare, int unde)
	{
		val = valoare;
		poz_in_ordcrono = unde;
	}

	nod& operator = (nod& sursa)
	{
		val = sursa.val;
		poz_in_ordcrono = sursa.poz_in_ordcrono;
		return *this;
	}

}hp[200000];

int dim = 0, ordcrono[200000];

void schimba(int& a, int& b)
{
	const int aux = a;
	a = b;
	b = aux;
}

void schimba_noduri(int pozhp1, int pozhp2)
{
	int poz_crono1 = hp[pozhp1].poz_in_ordcrono;
	int poz_crono2 = hp[pozhp2].poz_in_ordcrono;
	schimba(hp[pozhp1].val, hp[pozhp2].val);
	schimba(hp[pozhp1].poz_in_ordcrono, hp[pozhp2].poz_in_ordcrono);
	schimba(ordcrono[poz_crono1], ordcrono[poz_crono2]);
}

void urca(int pozhp)
{
	int tata_pozhp = (pozhp - 1) / 2;
	while (pozhp != 0 and hp[pozhp].val < hp[tata_pozhp].val )
	{
		schimba_noduri(pozhp, tata_pozhp);
		pozhp = tata_pozhp;
		tata_pozhp = (pozhp - 1) / 2;
	}
}

void coboara(int pozhp)
{
	int fiust_pozhp = pozhp * 2 + 1;
	if (fiust_pozhp <= dim - 1)
	{
		int fiudr_pozhp = pozhp * 2 + 2;
		if (fiudr_pozhp <= dim - 1 and hp[fiudr_pozhp].val < hp[fiust_pozhp].val)
		{
			schimba_noduri(pozhp, fiudr_pozhp);
			coboara(fiudr_pozhp);
		}
		else
		{
			schimba_noduri(pozhp, fiust_pozhp);
			coboara(fiust_pozhp);
		}
	}
}

void insert(int val)
{
	hp[dim].refresh(hp, val, dim);
	ordcrono[dim] = dim;
	urca(dim);
	dim++;
}

void sterge(int pozhp)
{
	schimba_noduri(pozhp, dim - 1);
	dim--;
	coboara(pozhp);
}

void afis_min()
{
	g << hp[0].val << "\n";
}

int main()
{
	int n;
	f >> n;
	for (int i = 0; i < n; i++)
	{
		shint task;
		f >> task;
		switch (task)
		{
		case 1:
		{
			int val;
			f >> val;
			insert(val);
		}
		break;
		case 2:
		{
			int pozcrono;
			f >> pozcrono;
			pozcrono--;
			sterge(ordcrono[pozcrono]);
			//std::cout << "  ordcrono[pozcrono] = " << ordcrono[pozcrono] << "  "; 
		}
		break;
		case 3:
		{
			afis_min();
		}
		}

		/*std::cout << "  | dupa instr " << i << ": ";
		for (int i = 0; i < dim; i++)
			std::cout << hp[i].val << " ";
		std::cout << "\n";*/
	}
	return 0;
}