Cod sursa(job #1034823)

Utilizator SzymonSidorSzymonSidor SzymonSidor Data 18 noiembrie 2013 06:26:00
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <fstream>
#include <vector>

#define MAX 200010
#define pb push_back

using namespace std;

int heapSize;
int poz[MAX];
int minHeap[MAX];
int el[MAX];

inline void heapUp(int nod) {
	if (nod == 1)
		return;

	if (el[minHeap[nod / 2]] > el[minHeap[nod]]) {
		swap(poz[minHeap[nod / 2]], poz[minHeap[nod]]);
		swap(minHeap[nod / 2], minHeap[nod]);

		heapUp(nod / 2);
	}
}

inline void heapDown(int nod) {
	if (nod * 2 > heapSize)
		return;

	int candidate = nod * 2;
	if (nod * 2 < heapSize && el[minHeap[nod * 2]] > el[minHeap[nod * 2 + 1]])
		candidate++;

	if (el[minHeap[nod]] > el[minHeap[candidate]]) {
		swap(poz[minHeap[candidate]], poz[minHeap[nod]]);
		swap(minHeap[candidate], minHeap[nod]);

		heapDown(candidate);
	}
}

int main() {
	ifstream cin("heapuri.in");
	ofstream cout("heapuri.out");

	int n;
	cin >> n;
	for (int i = 1; i <= n; i++) {
		int tip, x;
		cin >> tip;

		if (tip == 1) {
			cin >> x;

			el[++el[0]] = x;

			minHeap[++heapSize] = el[0];
			poz[el[0]] = heapSize;

			heapUp(heapSize);
		}
		else if (tip == 2) {
			cin >> x;

			int a = poz[x];

			swap(minHeap[a], minHeap[heapSize]);
			poz[minHeap[a]] = a;
			poz[minHeap[heapSize]] = heapSize;
			heapSize--;

			heapDown(a);
		}
		else cout << el[minHeap[1]] << "\n";
	}

	return 0;
}