struct Heap {
int capacity;
int heapSize;
int *tree; // the heap binary tree
int *pos; // pos[i] is the position of values[i] in items
float *p; // priority value of each heap element
};
void initHeap(struct Heap *heap, int capacity) {
heap->capacity = capacity;
heap->heapSize = 0;
heap->tree = malloc(sizeof(int)*(capacity+1));
heap->pos = malloc(sizeof(int)*(capacity+1));
heap->p = malloc(sizeof(float)*(capacity+1));
}
void betterInit(struct Heap *heap, int capacity) {
with (heap) { // doesn't exist
capacity = capacity;
heapSize = 0;
tree = malloc(sizeof(int)*(capacity+1));
pos = malloc(sizeof(int)*(capacity+1));
p = malloc(sizeof(float)*(capacity+1));
}
}
// update heap after a value is increased
void upHeap(struct Heap *heap, int i) {
int *tree = heap->tree, *pos = heap->pos;
float *p = heap->p;
int c, r;
c = pos[i]; // position of element i-th in heap
while (true) {
r = parent(c);
if (r==0 || p[tree[r]] >= p[i]) break; // if c is root, or priority(parent(c)) is > priority(c)
pos[tree[r]] = c; // pull the parent down to c
tree[c] = tree[r];
c = r;
}
tree[c] = i;
pos[i] = c;
}
So the 1st initHeap
looks long because I have to write heap->
a lot of times. And I wish to make it look shorter.
One solution is to write:
int *tree = heap->tree;
int *pos = heap->pos;
float *p = heap->p;
and then use tree, pos, p
. Are there more ways?