73 lines
1.7 KiB
C
73 lines
1.7 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
void swap(int *a, int *b);
|
|
void insert(int value, int *heap, int* size);
|
|
void delete(int *heap, int* size);
|
|
|
|
int main(){
|
|
int N;
|
|
scanf("%d",&N);
|
|
int *heap = (int*)malloc(sizeof(int)*(N+1));
|
|
int heap_size = 0;
|
|
while(N--){
|
|
int op;
|
|
scanf("%d",&op);
|
|
if(op==0) delete(heap, &heap_size);
|
|
else insert(op, heap, &heap_size);
|
|
}
|
|
|
|
free(heap);
|
|
return 0;
|
|
}
|
|
|
|
void swap(int *a, int *b){
|
|
int temp = *a;
|
|
*a = *b;
|
|
*b = temp;
|
|
}
|
|
|
|
void insert(int value, int *heap, int* size){
|
|
heap[++(*size)] = value;
|
|
int current = *size;
|
|
while(current != 1){
|
|
if((abs(heap[current]) < abs(heap[current/2]) ||
|
|
(abs(heap[current]) == abs(heap[current/2]) && heap[current]<heap[current/2]))){
|
|
swap(&heap[current], &heap[current/2]);
|
|
current /= 2;
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
void delete(int *heap, int* size){
|
|
if(*size==0){
|
|
printf("0\n");
|
|
return;
|
|
}
|
|
|
|
printf("%d\n",heap[1]);
|
|
heap[1] = heap[(*size)--];
|
|
|
|
int current = 1;
|
|
while (current * 2 <= *size) {
|
|
int child = current * 2;
|
|
|
|
if (child + 1 <= *size &&
|
|
((abs(heap[child + 1]) < abs(heap[child])) ||
|
|
(abs(heap[child + 1]) == abs(heap[child]) && heap[child + 1] < heap[child]))) {
|
|
child++;
|
|
}
|
|
|
|
if ((abs(heap[child]) < abs(heap[current])) ||
|
|
(abs(heap[child]) == abs(heap[current]) && heap[child] < heap[current])) {
|
|
swap(&heap[current], &heap[child]);
|
|
current = child;
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
} |