Cod sursa(job #554703)

Utilizator nr913Roman Alin nr913 Data 15 martie 2011 08:33:28
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
using namespace std;

#define ls(x) (x * 2)
#define rs(x) (x * 2 + 1)
#define ft(x) (x / 2)

struct HP {
	int v;
	int p;
} Heap[200000];
int cron[200000], n, m;

void sift(int x) {
	int son;
	do {
		son = 0;
		if (ls(x) <= n) {
			son = ls(x);
			if (rs(x) <= n && Heap[rs(x)].v < Heap[ls(x)].v)
				son = rs(x);
			if (Heap[son].v >= Heap[x].v)
				son = 0;
		}
		if (son) {
			cron[Heap[x].p] = son;
			cron[Heap[son].p] = x;
			HP aux = Heap[x];
			Heap[x] = Heap[son];
			Heap[son] = aux;
			x = son;
		}
	} while (son);
}

void percolate(int x) {
	HP key = Heap[x];
	while (x > 1 && key.v < Heap[ft(x)].v) {
		cron[Heap[ft(x)].p] = x;
		Heap[x] = Heap[ft(x)];
		x = ft(x);
	}
	Heap[x] = key;
	cron[key.p] = x;
}

void build_heap() {
	for (int i = n / 2; i > 0; --i)
		sift(i);
}

void heap_remove(int p) {
	int x = cron[p];
	Heap[x] = Heap[n];
	--n;
	if (x > 1 && Heap[x].v < Heap[ft(x)].v)
		percolate(x);
	else
		sift(x);
}

void heap_insert(int x) {
	Heap[++n].v = x;
	Heap[n].p = ++m;
	cron[m] = n;
	percolate(n);
}

int main() {
	ifstream cin("heapuri.in");
	ofstream cout("heapuri.out");
	int N, c, x;
	cin>>N;
	while (N) {
		cin>>c;
		if (c == 1) {
			cin>>x;
			heap_insert(x);
		} else if (c == 2) {
			cin>>x;
			heap_remove(x);
		} else {
			cout<<Heap[1].v<<"\n";
		}
		--N;
	}
	cout.close();
	cin.close();
	return 0;
}