Cod sursa(job #2762158)

Utilizator cosmin1812Nedelcu Adrian Cosmin cosmin1812 Data 5 iulie 2021 19:41:08
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include<fstream>
#include <iostream>
using namespace std;

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

int valori_heap[200001], h[200001], pozitie[200001];
int n, nr;


void urca(int nod) {

	if (nod > 1)
		if (valori_heap[h[nod]] < valori_heap[h[nod / 2]]) {

			swap(pozitie[h[nod]], pozitie[h[nod / 2]]);
			swap(h[nod], h[nod / 2]);
			urca(nod / 2);
		}
}


void adauga(int nod) {
	n++;
	valori_heap[n] = nod;
	nr++;
	h[nr] = n;
	pozitie[n] = nr;

	urca(nr);
}



void coboara(int nod) {

	int minim = nod;
	if (nr >= 2 * nod)
		if (valori_heap[h[2 * nod]] < valori_heap[h[minim]])
			minim = 2 * nod;

	if (nr >= 2 * nod + 1)
		if (valori_heap[h[2 * nod + 1]] < valori_heap[h[minim]])
			minim = 2 * nod + 1;

	if (minim != nod) {

		swap(h[nod], h[minim]);
		pozitie[h[minim]] = minim;
		pozitie[h[nod]] = nod;
		coboara(minim);
	}
}


void sterge(int nod) {

	valori_heap[h[pozitie[nod]]] = -1;
	urca(pozitie[nod]);
	h[1] = h[nr--];
	coboara(1);

}



int main() {

	int operatie, element;
	int nr_elem;
	f >> nr_elem;

	for (int i = 0; i < nr_elem; i++) {

		f >> operatie;

		if (operatie == 1) {

			f >> element;
			adauga(element);
		}
		else
		{
			if (operatie == 2) {

				int sterge_pozitie;
				f >> sterge_pozitie;
				sterge(sterge_pozitie);
			}
			else
			{
				if (operatie == 3)
					g << valori_heap[h[1]] << endl;
			}
		}


	}


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