Cod sursa(job #1089745)

Utilizator pulseOvidiu Giorgi pulse Data 21 ianuarie 2014 21:47:56
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <cstdio>

using namespace std;

#define NMAX 2000005

int n, k, questions;
int heap[NMAX], pos[NMAX], ord[NMAX];

inline int Father (int nod)
{
	return nod / 2;
}

inline int Right_Son (int nod)
{
	return nod * 2;
}

inline int Left_Son (int nod)
{
	return nod * 2 + 1;
}

void Swap (int i, int j)
{
	int aux = heap[i];
	heap[i] = heap [j];
	heap[j] = aux;

	aux = pos[ord[i]];
	pos[ord[i]] = pos[ord[j]];
	pos[ord[j]] = aux;

	aux = ord[i];
	ord[i] = ord[j];
	ord[j] = aux;
}

void Percolate (int i)
{
	while (i > 1 && heap[i] < heap[Father (i)])
	{
		Swap (i, Father (i));
		i = Father (i);
	}
}

void Sift (int i)
{
	int son;
	do
	{
		son = 0;
		if (Left_Son (i) <= n)
		{
			son = Left_Son (i);
			if (Right_Son (i) <= n && heap[son] > heap[Right_Son (i)])
				son = Right_Son (i);
			if (heap[son] > heap[i])
				son = 0;
		}
		if (son)
			Swap (i, son);
		i = son;
	} while (son);
}

void Insert (int x)
{
	n++;
	k++;
	heap[n] = x;
	pos[k] = n;
	ord[n] = k;
	Percolate (n);
}

void Cut (int x)
{
	int i = pos[x];
	Swap (i, n);
	n--;
	if (i > 1 && heap[i] < heap[Father (i)])
		Percolate (i);
	else
		Sift (i);
}

int main ()
{
	freopen ("heapuri.in", "r", stdin);
	freopen ("heapuri.out", "w", stdout);
	scanf ("%d", &questions);
	for (int i = 1, type, val; i <= questions; ++i)
	{
		scanf ("%d", &type);
		if (type == 3)
			printf ("%d\n", heap[1]);
		else
		{
			scanf ("%d", &val);
			if (type == 2)
				Cut (val);
			else
				Insert (val);
		}
	}
	return 0;
}