Cod sursa(job #613562)

Utilizator sima_cotizoSima Cotizo sima_cotizo Data 30 septembrie 2011 00:45:19
Problema Heapuri Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.33 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)
{
	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 && values[heap[f]] < values[heap[i*2+2]] )
		f = i * 2 + 2;
	if ( cmp(heap[f], heap[i]) )
	{
		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);
	for (i=0; i<T; ++i)
	{
		int x, op;
		fscanf(f, "%d", &op);
		switch ( op )
		{
		case 1:
			fscanf(f, "%d", values+i);
			heap[heap_n] = i;
			position[i] = heap_n;
			heap_push(heap_n);
			heap_n ++;
			break;
		case 2:
			fscanf(f, "%d", &x);
			-- x;
			heap_n --;			
			position[heap[heap_n]] = position[x];
			heap[position[x]] = heap[heap_n];
			heap_pop(position[x]);
			break;
		case 3:
			fprintf(g, "%d\n", values[heap[0]]);
			break;
		}
	}
	
	return 0;
}