Cod sursa(job #2018257)

Utilizator epermesterNagy Edward epermester Data 4 septembrie 2017 10:11:02
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include<fstream>
#include<vector>
using namespace std;

vector<int> heap;
vector<int> poz;
vector<int> hol;
int gSize = 0;

void heapAdd(int x) {
	int a = heap.size();
	heap.push_back(x);
	poz.push_back(gSize);
	gSize++;
	hol.push_back(a);
	while (a > 0) {
		int b;
		if (a % 2) b = a / 2;
		else b = a / 2 - 1;
		if (heap[a] < heap[b]) {
			int aux = heap[a];
			heap[a] = heap[b];
			heap[b] = aux;

			aux = poz[b];
			poz[b] = poz[a];
			poz[a] = aux;

			aux = hol[poz[a]];
			hol[poz[a]] = hol[poz[b]];
			hol[poz[b]] = aux;
			a = b;
		}
		else break;
	}
}

void heapDel(int x) {
	int b = hol[x];
	int size = heap.size() - 1;

	heap[b] = heap[size];
	heap.pop_back();				

	int aux = hol[poz[b]];
	hol[poz[b]] = hol[poz[size]];
	hol[poz[size]] = aux;

	poz[b] = poz[size];
	poz.pop_back();		

	
	while (b * 2 + 1 < size) {
		int a;
		if (b * 2 + 2 < size)
			if (heap[b * 2 + 2] < heap[b * 2 + 1])
				a = b * 2 + 2;
			else a = b * 2 + 1;
		else a = b * 2 + 1;
		if (heap[b] > heap[b*2+1]) {
			aux = heap[b];
			heap[b] = heap[a];
			heap[a] = aux;

			aux = hol[poz[b]];
			hol[poz[b]] = hol[poz[a]];
			hol[poz[a]] = aux;

			aux = poz[b];
			poz[b] = poz[a];
			poz[a] = aux;

			b = a;
		}
		else break;
	}
}

int main() {
	ifstream in("heapuri.in");
	ofstream out("heapuri.out");
	int N;
	in >> N;
	
	for(;N;--N)
	{
		short command;
		in >> command;
		switch (command)
		{
		case 1: 
			int nr;
			in >> nr;
			heapAdd(nr);
			break;
		case 2:
			int pozt;
			in >> pozt;
			heapDel(pozt-1);
			break;
		case 3:
			out << heap[0] <<"\n";
		default:
			break;
		}
	}
}