Cod sursa(job #1504684)

Utilizator experiment322Alexandru-Damian Manea experiment322 Data 18 octombrie 2015 01:48:15
Problema Heapuri Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.72 kb
#include <stdio.h>

struct heap {
	int tree[200000];
	int insertrank[200000];
	int insertno;
	int end;
} heap;

void swap(int *a, int *b)
{
	int aux = *a;
	*a = *b;
	*b = aux;
}

void heap_add(int newitem)
{
	int itempos = ++heap.end;
	heap.insertrank[++heap.insertno] = itempos;
	heap.tree[itempos] = newitem;
	int parent = (itempos - 1) / 2;
	int aux = 1;
	while (aux) {
		aux = 0;
		if (heap.tree[itempos] < heap.tree[parent]) {
			swap(&heap.tree[itempos], &heap.tree[parent]);
			swap(&heap.insertrank[itempos], &heap.insertrank[parent]);
			itempos = parent;
			parent = (itempos - 1) / 2;
			aux = 1;
		}
	}
}

void heap_del(int insitmno)
{
	int itempos = heap.insertrank[insitmno]
	heap.tree[itempos] = heap.tree[heap.end];
	heap.insertrank[itempos] = heap.insertrank[heap.end--];
	int aux = 1, smallest;
	while (aux) {
		aux = 0;
		smallest = 2 * itempos + 1;
		if (smallest < heap.end) {
			smallest = heap.tree[smallest] < heap.tree[smallest + 1] ? smallest : smallest + 1;
		} else if (smallest > heap.end) {
			smallest = 0;
		}
		if (heap.tree[smallest] < heap.tree[itempos] && smallest) {
			swap(&heap.tree[itempos], &heap.tree[smallest]);
			swap(&heap.insertrank[itempos], &heap.insertrank[smallest]);
			itempos = smallest;
			aux = 1;
		}
	}
}

int main(void)
{
	heap.end = heap.insertno = -1;
	int N;
	FILE *in = fopen("heapuri.in", "r");
	FILE *out = fopen("heapuri.out", "w");
	fscanf(in, "%d", &N);
	int i, op, aux;
	for (i = 0; i < N; ++i) {
		fscanf(in, "%d", &op);
		switch (op) {
			case 1:
				fscanf(in, "%d", &aux);
				heap_add(aux);
				break;
			case 2:
				fscanf(in, "%d", &aux);
				heap_del(aux - 1);
				break;
			case 3:
				fprintf(out, "%d\n", heap.tree[0]);
				break;
		}
	}
	fclose(in);
	fclose(out);
	return 0;
}