Cod sursa(job #504210)

Utilizator damgoodLincan Dan damgood Data 27 noiembrie 2010 01:26:53
Problema Heapuri Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.92 kb
#include <stdio.h>
#define file_in "heapuri.in"
#define file_out "heapuri.out"
#define MAX 200001

typedef struct heap {
	int value;
	int orderIndex;
} Heap;

Heap h[MAX];
int order[MAX], currentSize, totalInsert;

int father(int position)
{
	return position/2;
}

int leftSon(int position)
{
	return position*2;	
}

int rightSon(int position)
{
	return position*2+1;
}

int min()
{
	return h[1].value;
}

void swap( Heap *h1, Heap *h2, int position)
{
	int v = (*h1).value;
	int oi = (*h1).orderIndex;
	order[ h[position].orderIndex ] = father(position);
	Heap temp = *h1;
	*h1 = *h2;
	*h2 = temp;
	order[ h[position].orderIndex ] = position;
}

void up(int position)
{
	while( h[father(position)].value > h[position].value )
	{
		swap( &h[position], &h[father(position)], position );
		position = father(position);
	}
}

void down(int p)
{
	int min = 0;
	while(1)
	{
		if( leftSon(p) <= currentSize )
		{
			min = leftSon(p);
			if( rightSon(p) <= currentSize && h[min].value > h[rightSon(p)].value )
				min = rightSon(p);
			if( h[p].value > h[min].value )
				swap( &h[min], &h[p], p);
			p = min;
		}
		else break;
	} 
}

void delete(int which)
{
	h[order[which]] = h[currentSize--];
	down(order[which]);
}

void printHeap()
{
	int i;
	for(i = 1; i <= currentSize; i++)
		printf("%d:%d ; ", h[i].value, h[i].orderIndex);
	printf("\n");
	for(i = 1; i <= totalInsert; i++)
		printf("%d ", order[i]);
	printf("\n");
}

void insert(int element)
{
	h[++currentSize].value = element;
	h[currentSize].orderIndex = currentSize;
	order[totalInsert] = ++totalInsert;
	up(currentSize);
}

int main()
{
	FILE *in = fopen(file_in, "r");
	FILE *out = fopen(file_out, "w");
	int n, op, e;
	fscanf(in, "%d", &n);
	while(n--)
	{
		fscanf(in, "%d", &op);
		if( op == 1 )
		{
			fscanf(in, "%d", &e);
			insert(e);
		}
		else if( op == 2 )
		{
			fscanf(in, "%d", &e);
			delete(e);
		}
		else if( op == 3 )
			fprintf(out,"%d\n", min());
	}
	fclose(in);
	fclose(out);
	return 0;
}