Cod sursa(job #1832223)

Utilizator StefansebiStefan Sebastian Stefansebi Data 19 decembrie 2016 17:13:00
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include<fstream>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

//min heap
int heap[200009];
int alx[200009]; //elementul intrat al x lea in mult
int poz[200009]; //pozitia elementului 
int hsize = 0; //heap size

void insert(int elem) {
	int aux = hsize + 1; 
	hsize++; //size of the heap increases
	while (aux != 1 && elem < heap[aux / 2]) {
		heap[aux] = heap[aux / 2];
		poz[heap[aux]] = aux;
		aux = aux / 2;
	}
	heap[aux] = elem;
	poz[elem] = aux;
}

//sterg elementul din heap
void remove(int elem) {
	int aux = poz[elem];//radacin subarbore
	heap[aux] = heap[hsize]; //inlocuiesc cu ultimul element
	poz[heap[aux]] = aux;
	hsize--;//reduc dim heap 
	elem = heap[aux];//elementul care il coboram

	bool finished = false;
	while (!finished) {
		if (aux * 2 > hsize) {//leaf
			finished = true;
		}
		else if (aux * 2 + 1 > hsize) {//left son, but no right son
			if (heap[aux * 2] < elem) {
				heap[aux] = heap[aux * 2];
				poz[heap[aux]] = aux;
				aux = aux * 2;
			}
			else {
				finished = true;
			}
		}
		else {//both sons
			int l = aux * 2;
			int r = aux * 2 + 1;
			if (elem < heap[l] && elem < heap[r]) {
				finished = true;
			}
			else {
				if (l < r) {
					heap[aux] = heap[l];
					poz[heap[aux]] = aux;
					aux = l;
				}
				else {
					heap[aux] = heap[r];
					poz[heap[aux]] = aux;
					aux = r;
				}
			}
		}
	}
	heap[aux] = elem;
	poz[heap[aux]] = aux;
}

int main() {
	int n, q, a;
	int x = 1;
	fin >> n;
	for (int i = 1; i <= n; i++) {
		fin >> q;
		if (q == 1) {
			fin >> a;
			insert(a);
			alx[x] = a; x++;
		}
		else if (q == 2) {
			fin >> a;
			remove(alx[a]);
		}
		else if (q == 3) {
			fout << heap[1] << "\n";
		}
	}
}