Cod sursa(job #2287468)

Utilizator flibiaVisanu Cristian flibia Data 21 noiembrie 2018 21:51:39
Problema Heapuri Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <stdio.h>
#define inf (int) 1000000123

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

void push(int *heap, int *pos, int *input, int *heap_size, int p) {
	*heap_size = *heap_size + 1;
	int idx = *heap_size;
	heap[idx] = p;
	pos[p] = *heap_size;
	while (idx != 1) {
		if (input[heap[idx]] < input[heap[idx / 2]]) {
			swap(&heap[idx], &heap[idx / 2]);
			pos[heap[idx]] = idx;
			pos[heap[idx / 2]] = idx / 2;
			idx = idx / 2;
		} else break;
	}
}

void erase(int *heap, int *pos, int *input, int *heap_size, int p) {
	int idx = pos[p];
	input[heap[idx]] = inf;
	while ((idx * 2) <= *heap_size) {
		if ((idx * 2 + 1 > *heap_size)) {
			swap(&heap[idx], &heap[idx * 2]);
			pos[heap[idx]] = idx;
			pos[heap[idx * 2]] = idx * 2;
			idx = idx * 2;
		} else {
			if (input[heap[idx * 2]] < input[heap[idx * 2 + 1]]) {
				swap(&heap[idx], &heap[idx * 2]);
				pos[heap[idx]] = idx;
				pos[heap[idx * 2]] = idx * 2;
				idx = idx * 2;
			} else {
				swap(&heap[idx], &heap[idx * 2 + 1]);
				pos[heap[idx]] = idx;
				pos[heap[idx * 2 + 1]] = idx * 2 + 1;
				idx = idx * 2 + 1;
			}
		}
	}	
	*heap_size = *heap_size - 1;
}

int get_min(int *heap, int *input) {
	return input[heap[1]];
}

int main() {
	FILE* in = fopen("heapuri.in", "r");
	FILE* out = fopen("heapuri.out", "w");
	int heap[200100], pos[200100], input[200100], input_size, heap_size;
	int n;
	fscanf(in, "%d", &n);
	for (int i = 1; i <= n; i++) {
		int cod, x;
		fscanf(in, "%d", &cod);
		if (cod == 3) {
			fprintf(out, "%d\n", get_min(heap, input));
			continue;
		}
		if (cod == 1) {
			input_size++;
			fscanf(in, "%d", &input[input_size]);
			push(heap, pos, input, &heap_size, input_size);
		} else if (cod == 2) {
			fscanf(in, "%d", &x);
			erase(heap, pos, input, &heap_size, x);
		}
	}
	fclose(in);
	fclose(out);
	return 0;
}