Cod sursa(job #503905)

Utilizator cdascaluDascalu Cristian cdascalu Data 25 noiembrie 2010 17:06:37
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include<stdio.h>
#define MAX 200001
int n,cont,order[MAX],p;
struct bla
{
	int val,order;
}heap[MAX],aux;
int right_son(int x)
{
	return x*2 + 1;
}
int left_son(int x)
{
	return x*2;
}
int father(int x)
{
	return x/2;
}
void sift(int x)
{
	int son;
	do
	{
		son = 0;
		if(left_son(x) <= cont)
		{
			son = left_son(x);
			if(right_son(x) <= cont && heap[son].val > heap[right_son(x)].val)
				son = right_son(x);
		}
		if(heap[son].val >= heap[x].val)
			son = 0;
		
		if(son)
		{
			order[heap[son].order] = x;
			order[heap[x].order] = son;
			aux = heap[son];
			heap[son] = heap[x];
			heap[x] = aux;
			x = son;
		}
	}while(son);
}
void percolate(int x)
{
	while(heap[father(x)].val > heap[x].val && father(x))
	{
		order[heap[father(x)].order] = x;
		order[heap[x].order] = father(x);
		
		aux = heap[father(x)];
		heap[father(x)] = heap[x];
		heap[x] = aux;
		x = father(x);
	}
}
void insert(int x)
{
	heap[++cont].val = x;
	heap[cont].order = p+1;
	order[++p] = cont;
	percolate(cont);
}
void cut(int x)
{
	x = order[x];
	heap[x] = heap[cont--];
	sift(x);
	if(heap[father(x)].val > heap[x].val && father(x))
		percolate(x);
}
int main()
{
	FILE*f = fopen("heapuri.in","r");
	FILE*g = fopen("heapuri.out","w");
	fscanf(f,"%d",&n);
	int c,x;
	while(n--)
	{
		fscanf(f,"%d",&c);
		if(c == 1)
		{
			fscanf(f,"%d ",&x);
			insert(x);
		}
		if(c == 2)
		{
			fscanf(f,"%d",&x);
			cut(x);
		}
		if(c == 3)
		{
			fprintf(g,"%d\n",heap[1].val);
		}
	}
	fclose(f);
	fclose(g);
}