Cod sursa(job #2662941)

Utilizator vali_27Bojici Valentin vali_27 Data 24 octombrie 2020 21:35:09
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <iostream>
#include <fstream>
#define NMAX 200001

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

int heap[NMAX], val[NMAX], val_size, heap_size, poz[NMAX];

void upheap(int nod) {
	while (nod >= 0 && val[heap[nod]] < val[heap[(nod - 1) / 2]]) {
		std::swap(heap[nod], heap[(nod - 1) / 2]);
		poz[heap[nod]] = nod;
		poz[heap[(nod - 1) / 2]] = (nod - 1) / 2;

		nod = (nod - 1) / 2;
	}
}

int getIdxMin(int nod) {
	if (nod * 2 + 2 < heap_size)
		return val[heap[nod * 2 + 1]] < val[heap[nod * 2 + 2]] ? nod * 2 + 1 : nod * 2 + 2;
	return nod * 2 + 1;
}

void downheap(int nod) {
	while (nod < heap_size / 2) 
	{
		int idxMin = getIdxMin(nod);
		if (val[heap[nod]] > val[heap[idxMin]])
		{
			std::swap(heap[nod], heap[idxMin]);
			poz[heap[nod]] = nod;
			poz[heap[idxMin]] = idxMin;

			nod = idxMin;
		}
		else return;
	}
}

void insert(int x) {
	val[val_size] = x;
	heap[heap_size] = val_size;
	poz[val_size] = heap_size;

	upheap(heap_size);

	heap_size += 1;
	val_size += 1;
}

void deleteAt(int p) {
	val[p] = -1;
	upheap(poz[p]);

	poz[heap[0]] = -1;
	heap[0] = heap[heap_size - 1];
	heap_size -= 1;
	poz[heap[0]] = 0;

	downheap(0);
}
 

void citire() {
	int m;
	f >> m;
	for (int i = 0; i < m; ++i) {
		int tip, x;
		f >> tip;
		if (tip == 1) {
			f >> x;
			insert(x);
		}
		else if (tip == 2) {
			f >> x;
			deleteAt(x-1);
		}
		else {
			g << val[heap[0]] << '\n';
		}
	}
}

int main() {
	citire();
}