Cod sursa(job #542233)

Utilizator GodiesVlad Voicu Godies Data 25 februarie 2011 23:45:30
Problema Heapuri Scor 10
Compilator c Status done
Runda Arhiva educationala Marime 1.46 kb
#include <stdio.h>
#include <stdlib.h>

#define change(a, b, type) \
{\
	type aux; \
	aux = a; \
	a = b; \
	b = aux;\
}

#define maxv 200001

FILE *f, *g;
int maxheap;
int v[maxv];
int heap[maxv];
int poz[maxv];

void insert(int elem)
{
	int k, oldk;
	heap[ ++maxheap ] = elem;
	poz[elem] = maxheap; 
	k = maxheap;
	while (k > 0) {
		oldk = k>>1;
		if (v[heap[oldk]] > v[heap[k]]) {
			change(heap[k], heap[oldk], int);
			change(poz[heap[k]], poz[heap[oldk]], int);
		}
		else {
			break;
		}
		k = oldk;
	}
}

void removek(int elem)
{
	int k, oldk;
	k = elem;
	change(heap[k], heap[maxheap], int);
	change(poz[heap[k]], poz[heap[k]], int);
	maxheap--;
	while (k < maxheap) {
		oldk = k<<1;
		if ((v[heap[k]] > v[heap[oldk]]) && (oldk <= maxheap)) {
			change(heap[k], heap[oldk], int);
			change(poz[heap[k]], poz[heap[oldk]], int);
			k = oldk;
		}
		else {
			if ((v[heap[k]] > v[heap[oldk+1]]) && (oldk < maxheap)) {
				change(heap[k], heap[oldk+1], int);
				change(poz[heap[k]], poz[heap[oldk+1]], int);
				k = oldk + 1;
			}
			else {
				break;
			}
		}
	}
}


void citire()
{
	int x, i, k = 0, n;
	f = fopen("heapuri.in", "rt");
	g = fopen("heapuri.out", "wt");
	fscanf(f, "%d", &n);
	for (i = 1; i <= n; i++) {
		fscanf(f, "%d" , &x);
		if (x == 3) {
			fprintf(g, "%d\n" , v[heap[1]]);
		}
		if (x == 1) {
			fscanf(f, "%d", &v[++k]);
			insert(k);
		}
		if (x == 2) {
			fscanf(f, "%d", &x);
			removek(poz[x]);
		}
	}
	fclose(f);
	fclose(g);
}

int main()
{
	citire();
	return 0;
}