Cod sursa(job #1216398)

Utilizator pulseOvidiu Giorgi pulse Data 4 august 2014 15:10:12
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <cstdio>
#include <algorithm>

using namespace std;

const int nmax = 200005;
typedef int Heap;
Heap H[nmax];
int N, K, q, type, a, pos[nmax], ord[nmax];

int Father(int k)
{
	return (k >> 1);
}

int Left_Son(int k)
{
	return (k << 1);
}

int Right_Son(int k)
{
	return Left_Son(k) + 1;
}

void Swap(int a, int b)
{
	swap(H[a], H[b]);
	swap(pos[ord[a]], pos[ord[b]]);
	swap(ord[a], ord[b]);
}

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

void Sift(int k)
{
	int son;
	do
	{
		son = 0;
		if (Left_Son(k) <= N)
		{
			son = Left_Son(k);
			if (Right_Son(k) <= N && H[Right_Son(k)] < H[son])
				son = Right_Son(k);
			if (H[son] > H[k])
				son = 0;
		}
		if (son)
		{
			Swap(k, son);
			k = son;
		}
	} while(son);
}

void Insert(int k)
{
	++N;
	++K;
	H[N] = k;
	pos[K] = N;
	ord[N] = K;
	Percolate(N);
}

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

int main()
{
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	scanf("%d", &q);
	for (; q; --q)
	{
		scanf("%d", &type);
		if (type <= 2)
		{
			scanf("%d", &a);
			if (type == 1) Insert(a);
			else Cut(a);
		}
		else printf("%d\n", H[1]);
	}
	return 0;
}