Cod sursa(job #1405051)

Utilizator theprdvtheprdv theprdv Data 28 martie 2015 19:59:07
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>

using namespace std;

fstream fin("heapuri.in", ios::in);
fstream fout("heapuri.out", ios::out);

#define MAXN 200010
#define father(x) (int) x / 2
#define l_son(x) x * 2
#define r_son(x) x * 2 + 1
int A[MAXN], heap[MAXN], pos[MAXN], L;

void swap(int x, int y){
	pos[heap[x]] = y;  pos[heap[y]] = x;
	int aux = heap[x];  heap[x] = heap[y],  heap[y] = aux;
}
void percolate(int k){
	while (k > 1 && A[heap[father(k)]] > A[heap[k]])
		swap(k, father(k)),
		k = father(k);
}
void sift(int k){
	int son;
	do{
		son = 0;
		if (l_son(k) <= L && A[heap[l_son(k)]] < A[heap[k]])  son = l_son(k);
		if (r_son(k) <= L && A[heap[r_son(k)]] < A[heap[son]])  son = r_son(k);

		if (son)
			swap(k, son),
			k = son;
	} while (son);
}

int main()
{
	int n, op, x;
	fin >> n;
	for (int i = 1; i <= n; i++){
		fin >> op;
		if (op < 3) fin >> x;
		if (op == 1){
			A[++A[0]] = x;
			pos[A[0]] = ++L;
			heap[L] = A[0];
			percolate(L);
		}
		else if (op == 2){
			int p = pos[x];
			swap(p, L--);
			if (A[heap[p]] < A[heap[father(p)]] && (father(p) > 0))  percolate(p);
			else sift(p);
			heap[L + 1] = 0;
			pos[x] = 0;
		}
		else fout << A[heap[1]] << "\n";
	}

	fin.close();
	fout.close();
	return 0;
}