// minheap
#include<stdio.h>
#include<stdlib.h>
#define MAX_ELEMENTS 200 /* maximum heap size+l */
#define HEAP_FULL(n) (n == MAX_ELEMENTS - 1)
#define HEAP_EMPTY(n) (!n)
typedef struct {
int key;
char name[20];
/* other fields */
} element;
element heap[MAX_ELEMENTS];
int n = 0;
element pop(int *n);
void push(element item, int *n);
int main(void)
{
char choice;
element put;
for(;;)
{
printf("자료를 입력하시오. (num, name)\n");
scanf("%d",&put.key);
if(put.key==-1)
break;
scanf("%s",&put.name);
push(put,&n);
}
for(;;)
{
getchar();
printf("Root 노드의 레코드를 삭제할까요 ? : ");
scanf("%c",&choice);
if(choice=='y')
{
put=pop(&n);
printf("<%d,%s>\n",put.key,put.name);
}
else break;
}
return 0;
}
void push(element item, int *n)
{
int i;
if (HEAP_FULL(*n)) {
fprintf(stderr, "The heap is full. \n");
exit(EXIT_FAILURE);
}
i = ++(*n);
while ((i != 1) && (item.key < heap[i/2].key)) {
heap[i] = heap[i/2];
i /= 2;
}
heap[i] = item;
}
element pop(int *n)
{
int parent, child;
element item, temp;
if (HEAP_EMPTY(*n)) {
fprintf(stderr, "The heap is empty\n");
exit(EXIT_FAILURE);
}
item = heap[1];
temp = heap[( *n)--] ;
parent = 1;
child = 2;
while (child <= *n) {
if ((child < *n) && (heap[child].key > heap[child+1].key)) child++;
if (temp.key <= heap[child].key) break;
heap[parent] = heap[child];
parent = child;
child *= 2;
}
heap[parent] = temp;
return item;
}
'IT' 카테고리의 다른 글
스도쿠 판별 // 이게 완성본이 아닌건 함정 (0) | 2014.05.14 |
---|---|
파일 복사하기 (0) | 2014.05.14 |
winner tree (0) | 2014.05.14 |
dfs (0) | 2014.05.14 |
그래프 전은 자료구조 아니죠 ㅎㅎ (0) | 2014.05.14 |