18 int max_len = 1<<8, i;
25 for (i = 0; i < max_len; i++) (h->
id_to_pos)[i] = -1;
40 if (del)
for (i = 0; i < h->
len; i++) del((h->
heap)[i]);
47 max_len = max_len +
MAX(0.2*max_len, 10);
59 for (i = max_len0; i < max_len; i++) (h->
id_to_pos)[i] = -1;
64 #define ParentPos(pos) (pos - 1)/2
65 #define ChildrenPos1(pos) (2*(pos)+1)
66 #define ChildrenPos2(pos) (2*(pos)+2)
68 static void swap(
BinaryHeap h,
int parentPos,
int nodePos){
74 assert(parentPos < h->len);
77 parentID = pos_to_id[parentPos];
78 nodeID = pos_to_id[nodePos];
80 tmp = heap[parentPos];
81 heap[parentPos] = heap[nodePos];
84 pos_to_id[parentPos] = nodeID;
85 id_to_pos[nodeID] = parentPos;
87 pos_to_id[nodePos] = parentID;
88 id_to_pos[parentID] = nodePos;
101 if ((h->
cmp)(heap[parentPos], heap[nodePos]) == 1) {
102 swap(h, parentPos, nodePos);
103 nodePos = siftUp(h, parentPos);
109 static int siftDown(
BinaryHeap h,
int nodePos){
110 int childPos, childPos1, childPos2;
112 void **heap = h->
heap;
117 if (childPos1 > h->
len - 1)
return nodePos;
118 if (childPos1 == h->
len - 1) {
119 childPos = childPos1;
121 if ((h->
cmp)(heap[childPos1], heap[childPos2]) == 1){
122 childPos = childPos2;
124 childPos = childPos1;
128 if ((h->
cmp)(heap[nodePos], heap[childPos]) == 1) {
130 swap(h, nodePos, childPos);
131 nodePos = siftDown(h, childPos);
138 int len = h->
len,
id = len, flag, pos;
155 pos = siftUp(h, len);
185 if (pos < 0)
return NULL;
189 item = (h->
heap)[pos];
193 if (pos < h->len - 1){
194 swap(h, pos, h->
len - 1);
196 pos = siftUp(h, pos);
197 pos = siftDown(h, pos);
212 if (
id >= h->
max_len)
return -1;
214 if (pos < 0)
return -1;
218 pos = siftUp(h, pos);
220 pos = siftDown(h, pos);
233 if (pos < 0)
return NULL;
234 return (h->
heap)[pos];
239 void **heap = h->
heap;
243 for (i = 1; i < h->
len; i++){
245 assert((h->
cmp)(heap[i], heap[parentPos]) >= 0);
262 for (i = 1; i < h->
len; i++){
263 assert(mask[pos_to_id[i]] == -1);
264 mask[pos_to_id[i]] = 1;
265 assert(id_to_pos[pos_to_id[i]] == i);
276 for (i = 0; i < h->
len; i++){
278 fprintf(stderr,
"(%d) ",(h->
pos_to_id)[i]);
280 fprintf(stderr,
"\n");
284 fprintf(stderr,
"\nSpare keys =");
288 fprintf(stderr,
"\n");
void * BinaryHeap_extract_item(BinaryHeap h, int id)
int BinaryHeap_reset(BinaryHeap h, int id, void *item)
int(* cmp)(void *item1, void *item2)
BinaryHeap BinaryHeap_new(int(*cmp)(void *item1, void *item2))
#define ChildrenPos2(pos)
IntStack IntStack_new(void)
#define IntStack_get_length(s)
int BinaryHeap_insert(BinaryHeap h, void *item)
#define ChildrenPos1(pos)
void BinaryHeap_sanity_check(BinaryHeap h)
int IntStack_pop(IntStack s, int *flag)
void * BinaryHeap_extract_min(BinaryHeap h)
void IntStack_delete(IntStack s)
int IntStack_push(IntStack s, int i)
void * BinaryHeap_get_item(BinaryHeap h, int id)
void * BinaryHeap_get_min(BinaryHeap h)
void BinaryHeap_print(BinaryHeap h, void(*pnt)(void *))
void BinaryHeap_delete(BinaryHeap h, void(*del)(void *item))