Cod sursa(job #1306863)

Utilizator whoasdas dasdas who Data 31 decembrie 2014 16:44:35
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#define IA_PROB "heapuri"

#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>

#include <algorithm>

using namespace std;

class heap {
private:
	int last;
	vector<int> h, i2h, h2i;

	int p(int i) {
		return i / 2;
	}
	int c0(int i) {
		return i * 2 + 0;
	}
	int c1(int i) {
		return i * 2 + 1;
	}
	/* return the smallest of i, c0(i) and c1(i) */
	int smallest(int i) {
		int c0 = this->c0(i);
		int c1 = this->c1(i);

		int cs = c0;
		if (c1 <= last && h[c1] < h[c0]) {
			cs = c1;
		}
		if (cs <= last && h[cs] < h[i]) {
			return cs;
		}
		return i;
	}

public:
	heap() : last(0), h(1, -1), i2h(1, -1), h2i(1, -1) { }

	void percolate(int i) {
		while (h[i] < h[p(i)]) {
			swap(h[i], h[p(i)]);
			swap(h2i[i], h2i[p(i)]);
			swap(i2h[h2i[i]], i2h[h2i[p(i)]]);
			i = p(i);
		}
	}

	void sift(int i) {
		int s;
		while ((s = smallest(i)) != i) {
			swap(h[i], h[s]);
			swap(h2i[i], h2i[s]);
			swap(i2h[h2i[i]], i2h[h2i[s]]);
			i = s;
		}
	}

	void ins(int x) {
		last++;
		h.push_back(x);
		i2h.push_back(last);
		h2i.push_back(i2h.size() - 1);

		percolate(last);
	}

	void del(int x) {
		h[i2h[x]] = h[last];
		h2i[i2h[x]] = h2i[last];
		i2h[h2i[last]] = i2h[x];
		h.pop_back();
		h2i.pop_back();
		last--;

		percolate(i2h[x]);
		sift(i2h[x]);
	}

	int min() {
		return h[1];
	}
};

int main()
{
	freopen(IA_PROB".in", "r", stdin);
	freopen(IA_PROB".out", "w", stdout);

	int n;
	scanf("%d", &n);

	heap heap;

	for (int i = 0; i < n; i++) {
		int op, x;
		scanf("%d", &op);
		switch (op) {
		case 1:
			scanf("%d", &x);
			heap.ins(x);
			break;
		case 2:
			scanf("%d", &x);
			heap.del(x);
			break;
		case 3:
			x = heap.min();
			printf("%d\n", x);
			break;
		default:
			exit(1);
		}
	}

	return 0;
}