Cod sursa(job #2124622)

Utilizator epermesterNagy Edward epermester Data 7 februarie 2018 13:44:46
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include<fstream>
#include<vector>
using namespace std;

struct numbers {
	int value;
	int *poz;
};

vector<numbers> heap;
int ido[1000000], t = 0;

void swap(int poz1, int poz2) {
	int aux = heap[poz1].value;
	heap[poz1].value = heap[poz2].value;
	heap[poz2].value = aux;

	aux = *heap[poz1].poz;
	*heap[poz1].poz = *heap[poz2].poz;
	*heap[poz2].poz = aux;

	int *p = heap[poz1].poz;
	heap[poz1].poz = heap[poz2].poz;
	heap[poz2].poz = p;
}

void heapify(int i) {
	int n = heap.size();
	if (n <= 1) return;
	int j = i * 2 + 1;
	if (i * 2 + 2 < n && heap[i * 2 + 2].value < heap[j].value)
		j = i * 2 + 2;
	if (heap[i].value > heap[j].value)
		swap(i, j);
	if (j <= n / 2 - 1) heapify(j);
}


void heapAdd(int x) {
	int j = heap.size();
	numbers temp;
	ido[t] = j;
	temp.poz = &ido[t++];
	temp.value = x;
	heap.push_back(temp);

	if (j >= 1) {
		swap(0, j);
		heapify(0);
	}
}

void heapDel(int i) {
	int j = heap.size() - 1;
	if (j == ido[i])
		heap.pop_back();
	else {
		swap(ido[i], j);
		heap.pop_back();
		if (ido[j] * 2 + 1 < j) heapify(ido[j]);
	}
}

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].value << "\n";
		default:
			break;
		}
	}
}