I Dijkstra's algorithm we need to maintain heap for vertices who are not finalised. We need to modify the value of keys in the min heap. How can we do that without using custom heap written ourselves, but instead using Standard heap library like Heapq in python. I found this on stackoverflow but it is linear time to modify, can we do in logarithmic time complexity for decrease key? Any answer related to c++ or python will be awesome.
When I implement Dijkstra using heap, I don't erase an old value. Instead, when I get a value from the heap, I check if it is actual.
In other words, I do something like this. Here
d
is the array of distances,q
is the max heap with key{-d[v], v}
The fact that complexity is the same can be proven.
Thanks that is a very nice idea.
This is a very neat implementation of the inbuilt priority_queue for Dijkstra's:
https://cp-algorithms.com/graph/dijkstra_sparse.html#toc-tgt-3
I think, using make_heap() and pop_heap() instead of priority_queue<> can help.
In C++, if you want to modify heap element in logarithm time, there's more heaps in "policy based data structure" library but the constant seems to be big. Also you can use a set so you can erase the old element and insert the new element, which many people prefer to use.