Cod sursa(job #627937)

Utilizator sima_cotizoSima Cotizo sima_cotizo Data 30 octombrie 2011 23:42:16
Problema Heapuri Scor 40
Compilator c Status done
Runda Arhiva educationala Marime 1.26 kb
#include <stdio.h>

#define HMAX 200010
#define NMAX 200010

int position[NMAX];
int values[NMAX];
int heap[HMAX];
int heap_n;

int cmp(int x, int y)
{
	return values[x] < values[y];
}

inline void swap(int *x, int *y)
{ /* codul merge acum :) */
	int r = *x;
	*x = *y;
	*y = r;
}

void heap_push(int i)
{
	if ( i == 0 )
		return;
	int t = (i-1) / 2;
	if ( cmp(heap[i], heap[t]) )
	{
		swap(position + heap[i], position + heap[t]);
		swap(heap + i, heap + t);
		heap_push(t);
	}
}

void heap_pop(int i)
{
	if ( i*2+1 >= heap_n )
		return;
	int f = i*2+1;
	if ( i*2+2 < heap_n && cmp(heap[i*2+2],heap[f]) )
		f = i*2+2;
	if ( 1 )
	{
		swap(position + heap[f], position + heap[i]);
		swap(heap + f, heap + i);
		heap_pop(f);
	}
}

int main()
{
	int T, i;
	FILE *f = fopen("heapuri.in", "rt");
	FILE *g = fopen("heapuri.out", "wt");

	heap_n = 0;

	fscanf(f, "%d", &T);
	int ord = 0;
	for (i=0; i<T; ++i)
	{
		int x, op;
		fscanf(f, "%d", &op);
		switch ( op )
		{
		case 1:
			fscanf(f, "%d", values+ord);
			heap[heap_n] = ord;
			position[ord] = heap_n;
			heap_push(heap_n);
			heap_n ++;
			ord++;
			break;
		case 2:
			fscanf(f, "%d", &x);
			-- x;
			heap_pop(position[x]);
			heap_n --;			
			break;
		case 3:
			fprintf(g, "%d\n", values[heap[0]]);
			break;
		}
	}
	
	return 0;
}