Cod sursa(job #389265)

Utilizator mathboyDragos-Alin Rotaru mathboy Data 1 februarie 2010 13:08:23
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 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 && L <= D) minim = L;
	if (A [H [R]] < key && R <= D && L <= D && A [H [R]] < A [H [L]]) 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 K)
{	
	H [K] = H [D]; 
	--D;
	if (A [H [K]] < A [H [father(K)]] && father (K))
		upheap (K, A [H [K]]);
    else 
		downheap (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;
				upheap (D, A [N]);
			}
			else if (tip == 2)
			{   
				//printf ("** ");
				cut (Pos [x]);
				//printf ("pozitia: %d\n", Pos [x]);
			}
			//for (int i = 1; i <= D; i++) printf ("%d ", A[H [i]]);
			//printf ("\n");
		}
	}
	return 0;
}