Cod sursa(job #2014851)

Utilizator epermesterNagy Edward epermester Data 24 august 2017 15:22:16
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include<fstream>
#include<vector>
using namespace std;

vector<int> heap;
vector<int> poz;
vector<int> hol;

void heapAdd(int x) {
	int size = heap.size();
	heap.push_back(x);
	poz.push_back(size);
	hol.push_back(size);
#define a size
	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;
	}
}

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) {
		if (heap[b] > heap[b * 2 + 1]) {
			aux = heap[b];
			heap[b] = heap[b*2+1];
			heap[b * 2 + 1] = aux;

			aux = hol[poz[b]];
			hol[poz[b]] = hol[poz[b*2+1]];
			hol[poz[b*2+1]] = aux;

			aux = poz[b];
			poz[b] = poz[b*2+1];
			poz[b*2+1]=aux;

			b = b * 2 + 1;
		}
		else if (b * 2 + 2 < size && heap[b] > heap[b * 2 + 2]) {
			aux = heap[b];
			heap[b] = heap[b * 2 + 2];
			heap[b * 2 + 2] = aux;

			aux = hol[poz[b]];
			hol[poz[b]] = hol[poz[b * 2 + 2]];
			hol[poz[b * 2 + 2]] = aux;

			aux = poz[b];
			poz[b] = poz[b * 2 + 2];
			poz[b * 2 + 2] = aux;

			b = b * 2 + 2;
		}
		else break;
	}
}

int main() {
	ifstream in("heapuri.in");
	ofstream out("heapuri.out");
	int N;
	in >> N;

	short command;
	in >> command;

	while(!in.eof())
	{
		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;
		}
		in >> command;
	}
}