Wikipedia of Dijkstra算法有以下伪代码,它使用最小优先级队列:
1 function Dijkstra(Graph, source):
2 dist[source] ← 0 // Initialization
3
4 create vertex priority queue Q
5
6 for each vertex v in Graph:
7 if v ≠ source
8 dist[v] ← INFINITY // Unknown distance from source to v
9 prev[v] ← UNDEFINED // Predecessor of v
10
11 Q.add_with_priority(v, dist[v])
12
13
14 while Q is not empty: // The main loop
15 u ← Q.extract_min() // Remove and return best vertex
16 for each neighbor v of u: // only v that are still in Q
17 alt ← dist[u] + length(u, v)
18 if alt < dist[v]
19 dist[v] ← alt
20 prev[v] ← u
21 Q.decrease_priority(v, alt)
22
23 return dist, prev
然而,目前还不清楚decrease_priority
如何在对数时间内实现。有人愿意帮忙吗?
这取决于您使用的数据结构,但decrease_priority
可以通过使用min-heap以O(log n)时间复杂度实现。例如,我有以下堆:
如果我想将节点i=8的优先级从25降低到1,我首先改变它的优先级值,但是之后我仍然需要重新heapify来维护堆属性(root