Cod sursa(job #389110)

Utilizator mathboyDragos-Alin Rotaru mathboy Data 31 ianuarie 2010 21:44:11
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 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 upheap (int k, int key)
{
	int F;
    F = father (k);
	if ( key < A [H [F]] && k > 1) // HF :)
	{
		Pos [H[k]] = k >> 1;
		Pos [H[F]] = k;
		swap (H [k], H [F]);
		upheap (F, key);
	}
}
void downheap (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;
	//printf ("%d %d %d\n", minim, k, D);
	if (minim != k && k < D) {
		Pos [H[k]] = minim;
		Pos [H[minim]] = k;
		swap (H [k], H [minim]);
		downheap (minim, key);
	}
}
void cut (int &N, int K)
{	
	if (K > 1) {
	H [K] = H [N]; 
	--N;
	if (A [H [K]] < A [H [father(K)]] && father (K) > 0)
		upheap (Pos [K], A [H [K]]);
    else 
		downheap (Pos [K], A [H [K]]);
	}
	else {
		if ( H [2] < H [3] ) {
			H [1] = H [2];
			--N;
			Pos [H [2]] = 0;
		}
		else if (H [3] < H [2]) {
			H [1] = H [3];
			-- N;
			Pos [H [3]] = 0;
		}
	}
}
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;
				upheap (D, A [N]);
			}
			else if (tip == 2)
			{   
				//printf ("** ");
				A [x] = -1;
				cut (D, Pos [x]);
				//printf ("pozitia: %d\n", Pos [x]);
			}
			//for (int i = 1; i <= D; i++) printf ("%d ", A[H [i]]);
			//printf ("\n");
		}
	}
	return 0;
}