Mai intai trebuie sa te autentifici.

Cod sursa(job #279596)

Utilizator cotofanaCotofana Cristian cotofana Data 12 martie 2009 21:26:58
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <stdio.h>
#define dim 200100

int n, m, h[dim], poz[dim], l, a[dim];

inline int father(int x)
{
	return x/2;
}

inline int left_son(int x)
{
	return x*2;
}

inline int right_son(int x)
{
	return x*2+1;
}

inline int min()
{
	return a[h[1]];
}

void swap(int &a, int &b)
{
	int t;
	t=a, a=b, b=t;
}

void sift(int k)
{
	int son;
	do
	{
		son=0;
		if (left_son(k)<=n)
			son=left_son(k);
		if (right_son(k)<=n && a[h[left_son(k)]]>a[h[right_son(k)]])
			son=right_son(k);
		if (a[h[son]]>=a[h[k]]) son=0;
		if (son)
		{
			swap(poz[h[son]], poz[h[k]]);
			swap(h[son], h[k]);
			k=son;
		}
	} while (son);
}

void percolate(int k)
{
	int key=a[h[k]];
	while (key<a[h[father(k)]] && father(k))
	{
		swap(poz[h[k]], poz[h[father(k)]]);
		swap(h[k], h[father(k)]);
		k=father(k);
	}
}

void cut(int k)
{
	a[k]=0
	;
	h[poz[k]]=h[n--];
	poz[h[n+1]]=poz[k];
	if (k>1 && a[h[k]]<a[h[father(k)]]) percolate(k);
	else sift(poz[k]);
	poz[k]=0;
}

void insert(int key)
{
	a[++l]=key;
	h[++n]=l;
	poz[l]=n;
	percolate(n);
}

int main()
{
	int c, x;
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	scanf("%d\n", &m);
	for (; m; m--)
	{
		scanf("%d", &c);
		if (c==1)
		{
			scanf(" %d\n", &x);
			insert(x);
		}
		else if (c==2)
		{
			scanf(" %d\n", &x);
			cut(x);
		}
		else printf("%d\n", min());
	}
	return 0;
}