Single-Source Shortest-Paths Problem on a weighted graph G=(V, E)
主要学习了《Introduction to Algorithms》3rd,24章
1)Dijkstra Algorithm
all edges weights are nonnegative, w(u, v) >= 0 for each edge (u, v) ∈ E
「松弛Relaxation」, approximation to the correct distance is gradually replaced by more accurate values until eventually reaching the optimum solution.
(from wiki)
DIJKSTRA(G, w, s) – Graph, weight, source vertex
weight可以用「Adjacency LinkList」「Adjacency Matrix」表征
INITIALIZE-SINGLE-SOURCE(G, s)
S = ∅ // 空集,算法意义上指源点到所有顶点的距离正无穷
Q = G.V // Queue,未处理的目标顶点序列
while(Q ≠ ∅) // 1...|V|
u = EXTRACT-MIN(Q) // 选取总距离最近的顶点,O(V) for array
S = S ∪ u
for each vertex v ∈ G.adj[u] // totally E times operation
RELAX(u, v, w) // 更新到“新”邻接顶点的最短总距离
都以「BFS」为基底,与Prim有些像
「Prim」不断拓展并候选邻接点,比较并选取到临点最轻的边
「Dijkstra」不断拓展并候选邻接点,比较并更新总距离,选取最近的点
The running time of Dijkstra algorithm depends on how we implement the 「Min-Priority Queue」.
*「Array」, O(V^2 + E) = O(V^2)
「Min-Priority Queue with a binary min-heap」, O((V+E)lgV) = O(ElgV)
「Min-Priority Queue with a Fibonacci heap」, O(VlgV + E)
猴子也能懂:目标宏远,步步为营
2)Bellman-Ford Algorithm
slower than Dijkstra, capable of handling negative weights
「Relaxation」
https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
Dijkstra’s algorithm uses a priority queue to greedily select the closest vertex that has not yet been processed, and performs this relaxation process on all of its outgoing edges; by contrast, the Bellman–Ford algorithm simply relaxes all the edges, and does this |V|-1 times, where |V| is the number of vertices in the graph.
(from book)
BELLMAN-FORD(G, w, s)
INITIALIZE-SINGLE-SOURCE(G, s) // 初始依然是距离所有其他顶点正无穷
for i = 1 to |G.V| - 1 // 所有顶点扫一遍,进行核心松弛计算
for each edge(u, v) ∈ G.E // 每次对全边做优化...第一次一定是源的邻接顶点变得可计算...第二次逐渐多起来
RELAX(u, v, w) // 如果此边的u.d+w(u,v)<v.d,则更新
for each edge(u, v) ∈ G.E // 负环校验
if v.d > u.d + w(u, v) // 扫了辣么多次,这式子还能成立!?
return false // --只可能是负环(有负权边的死循环)
return true
猴子也能懂:刷的飞起,负环狗带
O(VE), number of vertices and edges respectively