Cod sursa(job #1483786)

Utilizator mike93Indricean Mihai mike93 Data 9 septembrie 2015 22:10:29
Problema Heapuri Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.54 kb
#include <stdio.h>
#include <stdlib.h>

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

int insert(int* h, int val, int* last) {
	*last = *last + 1;
	h[*last] = val;
	int pos = *last;
	while(pos > 1) {
		if(h[pos / 2] > h[pos]) {
			swap(&h[pos / 2], &h[pos]);
			pos = pos / 2;
		} else {
			break;
		}
	}
	return pos;
}

void delete(int* h, int pos, int* last) {
	swap(&h[pos], &h[*last]);
	h[*last] = 0;
	*last = *last - 1;
	while(pos < *last) {
		if(2 * pos > *last) {
			break;
		} else if((2 * pos + 1) > *last) {
			if(h[2 * pos] < h[pos]) {
				swap(&h[2 * pos], &h[pos]);
				pos = 2 * pos;
			} else {
				break;
			}
		} else if((h[2 * pos] < h[pos]) || (h[2 * pos + 1] < h[pos])) {
			if(h[2 * pos] < h[2 * pos + 1]) {
				swap(&h[2 * pos], &h[pos]);
				pos = 2 * pos;
			} else {
				swap(&h[2 * pos + 1], &h[pos]);
				pos = 2 * pos + 1;
			}
		}
	}
}

int main() {
	FILE* fin = fopen("heapuri.in", "r");
	int n;
	fscanf(fin, "%d\n", &n);
	fout = fopen("heapuri.out", "w");
	
	int* heap = malloc(n * sizeof(int));
	int* tab = malloc((n + 1) * sizeof(int));
	int last = 0;
	int N = 1;
	int i;
	int type, val;
	for(i=0; i<n; i++) {
		fscanf(fin, "%d ", &type);
		if(type == 1) {
			fscanf(fin, "%d\n", &val);
			tab[N] = insert(heap, val, &last);
			N++;
		} else if(type == 2) {
			fscanf(fin, "%d\n", &val);
			delete(heap, tab[val], &last);
		} else {
			fprintf(fout, "%d\n", heap[1]);
		}
	}
	
	free(tab);
	free(heap);
	fclose(fin);
	fclose(fout);
	return 0;
}