Reputation: 1911
At least a couple of answers recommend using the STL heap functions to implement the priority queue in Dijkstra's algorithm:
Performance of Dijkstra's algorithm implementation
Implementing Dijkstra's Algorithm
What's the best way to reorder vertices in the heap (line 19) given that the STL doesn't include a heap function for updating keys?
Upvotes: 1
Views: 3653
Reputation: 18572
I guess there are a few ways to do it.
You could manually do the sift-up operation and basically carry the value to the top of the heap, pop it and then push it back on the heap with its new value.
You could update the value and do a make_heap again on the heap, assuming that make_heap is designed to be efficient when the heap is "almost a heap" already.
You could mark the node that is in the heap with some flag to indicate that it is no longer valid, then push a new element with the new value on the heap. Then, every time you pop an element from the heap you check the flag for validity and ignore any invalid element.
Otherwise, you could use another heap implementation that does have update functionality. For example, Boost.Graph library includes, in its details (boost/graph/detail folder) a d_ary_heap.hpp header which implements a D-Ary Heap Indirect implementation which does have an update function that is logN. This is used in the BGL implementation of Dijkstra and A*, which you could use directly as well instead of implementing your own.
Upvotes: 1
Reputation: 30480
You need to let the vertex 'bubble up' through the heap (swapping it with its parent as needed) until it reaches its new position in the heap.
In pseudo-c++ adapted from Introduction to Algorithms 2nd ed. pg. 140:
heap[pos] = new_weight;
while (pos > 0 && heap[parent(pos)] > heap[pos]) {
swap(heap[parent(pos)], heap[pos]);
pos = parent(pos);
}
where int parent(int pos) { return (pos-1)/2; }
Upvotes: 5