How to implement O(logn) decrease-key operation for min-heap based Priority Queue?

前端 未结 4 1582
孤街浪徒
孤街浪徒 2020-12-04 10:59

I am working on an application that demonstrates the Djikstra\'s algorithm, and to use it, I need to restore the heap property when my elements\' value is decreased

4条回答
  •  情深已故
    2020-12-04 11:36

    Per this SO question it is unnecessary to have a decrease-key method in order to implement Dijkstra's Algorithm.

    You can simply add an item to the priority queue as many times as necessary and keep track of which nodes you have visited to weed out the duplicates. The first time you actually visit a node by popping it off of the queue, you have found the shortest path to that node and can ignore all future occurrences of it on the priority queue.

    Having many extra nodes on the priority queue is not much of a problem because it is an O(log N) structure. (You have to do about 20 comparisons for 1 million items and 30 comparison for 1 billion items.)

    Edit: Following up on this question later, I'm a bit disappointed by my answer: all of those things will have to come off of the queue unless you do some special canipulations later. Like many things in life, it comes down to how you manage your memory and the costs associated with doing so. But the general point remains: decrease-key is not necessary, even if it might be desirable.

提交回复
热议问题