Cod sursa(job #388956)

Utilizator mathboyDragos-Alin Rotaru mathboy Data 31 ianuarie 2010 15:25:08
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Algorithm Day #1 Marime 1.45 kb
#include <cstdio>
#include <algorithm>
#define DIM 200005 
using namespace std;

int H [DIM], Pos [DIM], A [DIM], N, D;
inline int left (int x) { return (x << 1) ;}
inline int right (int x) { return ((x << 1) + 1);}
inline int father (int x) { return (x >> 1);}

void insert_up (int k, int key)
{
	int F;
    F = father (k);
	if ( key < A [H [F]] && k > 1) // HF :)
	{
		Pos [H[k]] = F;
		Pos [H[F]] = k;
		swap (H [k], H [F]);
		insert_up (F, key);
	}
}
void insert_down (int k, int key)
{
	int L, R, minim = k;
	L = left (k);
	R = right (k);
	if ( A [ H [L] ] < key) minim = L;
	if ( A [ H [R] ] < A [H [L]] && A [H [R]] < key) minim = R;
	if (minim != k && k < N ) {
		Pos [H[k]] = minim;
		Pos [H[minim]] = k;
		swap (H [k], H [minim]);
		insert_down (minim, key);
	}
}
void cut (int &N, int K)
{	
	H [K] = H [N]; // OMG ! HD? :))
	--N;
	insert_up (K, A [H [K]]);
    insert_down (K, A [H [K]]);
}
int main ()
{
	int x, M, tip;
	freopen ("heapuri.in", "r", stdin);
	freopen ("heapuri.out", "w", stdout);
	scanf ("%d\n", &M);
	for ( ; M--; ) {
		scanf ("%d", &tip);
		if (tip == 3) printf ("%d\n", A [ H[1] ]);
		else
		{
			scanf ("%d", &x);
			if (tip == 1)
			{   
				A [++N] = x;
				H [++D] = N;
				Pos [N] = D;
				insert_up (D, A [N]);
			}
			else if (tip == 2)
			{   
				//printf ("** ");
				cut (D, Pos [x]);
				//printf ("pozitia: %d\n", Pos [x]);
				A [x] = -1;
			}
		}
	}
	return 0;
}