Cod sursa(job #486702)

Utilizator Cristi09Cristi Cristi09 Data 22 septembrie 2010 16:22:10
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include<stdio.h>
#define NMAX 200001
int heap[NMAX],order[NMAX],n,cont=0,aux,ind_order;
int left_son(int x)
{
	return x*2;
}
int right_son(int x)
{
	return x*2+1;
}
int father(int x)
{
	return x/2;
}
void sift(int x)
{
	int son;
	do
	{
		son = 0;
		if(left_son(x) <= cont && heap[left_son(x)] < heap[x])
		{	
			son = left_son(x);
			if(right_son(x) <= cont && heap[right_son(x)] < heap[left_son(x)])
			{
				son = right_son(x);
			}
		}
		if(son)
		{
			aux = heap[x];
			heap[x] = heap[son];
			heap[son] = aux;
		}
	}
	while(son);
}
void percolate(int x)
{
	while(father(x) > 0 && heap[father(x)] > heap[x])
	{
		aux = heap[father(x)];
		heap[father(x)] = heap[x];
		heap[x] = aux;
		x = father(x);
	}
}
void insert(int x)
{
	heap[++cont] = x;
	order[++ind_order] = x;
	percolate(cont);
}
void cut(int x)
{
	int i=1;
	x = order[x];
	for(;i<=cont && heap[i]!=x;++i);
	
	x = i;
	heap[x] = heap[cont];
	heap[cont--] = 0;
	
	if(x > 1 && heap[father(x)] > heap[x])
		percolate(x);
	else
		sift(x);
}
int main()
{
	FILE*g = fopen("heapuri.out","w"); 
	FILE*f = fopen("heapuri.in","r");
	fscanf(f,"%d",&n);
	int i=1,tip,x;
	
	for(;i<=n;++i)
	{
		fscanf(f,"%d",&tip);
		if(tip == 1)
		{
			fscanf(f,"%d",&x);
			insert(x);
		}
		if(tip == 2)
		{
			fscanf(f,"%d",&x);
			cut(x);
		}
		if(tip == 3)
		fprintf(g,"%d\n",heap[1]);
	}
	fclose(f);
	fclose(g);
	return 0;
}