Cod sursa(job #278455)

Utilizator Omega91Nicodei Eduard Omega91 Data 12 martie 2009 12:34:21
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <cstdio>
#include <cstring>

class heap {
	struct tree_element {
		int val, hist;
	};
	static const int NMAX = 200001;
	tree_element tree[NMAX];
	int sz;
	int history[NMAX], hisz;
	
	template <class T>
	void swap(T &a, T &b) {
		T aux;
		aux = a;
		a = b;
		b = aux;
	};
	
	void downsort(int);
	void upsort(int);
	
	public:
		heap() { sz = 0; tree[0].val = -1; hisz = 0; memset(history, 0, sizeof(int) * NMAX); };
		void insert(int);
		void remove(int);
		int query() { return tree[1].val; };
	
};

void heap::downsort(int parrent)
{
	int son, h;
	h = tree[parrent].hist;
	while((parrent << 1) <= sz) {
		son = tree[parrent << 1].val < tree[(parrent << 1) + 1].val ? parrent << 1 : (parrent << 1) + 1;
		if (tree[parrent].val > tree[son].val) {
			swap(tree[parrent], tree[son]);
			swap(history[tree[parrent].hist], history[tree[son].hist]);
		}
		else break;
		parrent = son;
	}
	//history[h] = parrent;
}

void heap::upsort(int son)
{
	int parrent, h;
	h = tree[son].hist;
	parrent = son >> 1;
	while(tree[son].val < tree[parrent].val) {
		swap(tree[son], tree[parrent]);
		swap(history[tree[son].hist], history[tree[parrent].hist]);
		son = parrent;
		parrent >>= 1;
	}
	//history[h] = son;
}

void heap::insert(int x)
{
	tree[++sz].val = x;
	tree[sz].hist = ++hisz;
	history[hisz] = sz;
	upsort(sz);
}

void heap::remove(int k)
{
	history[tree[sz].hist] = history[k];
	tree[history[k]] = tree[sz--];

	downsort(history[k]);
}


int main()
{
	int N, i, nr, type;
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	heap h;
	scanf("%d\n", &N);
	for (i = 0; i != N; ++i) {
		scanf("%d", &type);
		switch (type) {
			case 1:
				scanf("%d\n", &nr);
				h.insert(nr);
				break;
			case 2:
				scanf("%d\n", &nr);
				h.remove(nr);
				break;
			case 3:
				printf("%d\n", h.query());
		}
	}
	return 0;
}