Pagini recente » Cod sursa (job #421163) | Cod sursa (job #1476740) | Cod sursa (job #2066985) | Cod sursa (job #959079) | Cod sursa (job #1483790)
#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;
}
} else {
break;
}
}
}
int main() {
FILE* fin = fopen("heapuri.in", "r");
int n;
fscanf(fin, "%d\n", &n);
FILE* 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;
}