Cod sursa(job #1034808)

Utilizator SzymonSidorSzymonSidor SzymonSidor Data 18 noiembrie 2013 05:42:51
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <stdio.h>
#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 (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() {

	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);

	int n;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		int tip, x;
		scanf("%d", &tip);

		if (tip == 1) {
			scanf("%d", &x);

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

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

			heapUp(heapSize);
		}
		else if (tip == 2) {
			scanf("%d", &x);

			swap(poz[minHeap[heapSize]], poz[x]);
			swap(minHeap[poz[x]], minHeap[heapSize]);
			heapDown(poz[x]);

			heapSize--;
		}
		else printf("%d\n", el[minHeap[1]]);
	}
}