Suppose we are given a directed graph G = (V, E)
with potentially positive and negative edge lengths, but no negative cycles. Let s ∈ V
be a given source
vertex. How to design an algorithm for the single-source shortest path problem that runs in time O(k(|V | + |E|))
if the shortest paths from s to any other vertex takes at most k edges
?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Here`s O(k(|V | + |E|)) approach:
- We can use Bellman-Ford algorithm with some modifications
- Create array D[] to store shortest path from node s to some node u
- initially D[s]=0, and all other D[i]=+oo (infinity)
- Now after we iterate throught all edges k times and relax them, D[u] holds shortest path value from node s to u after <=k edges
Because any s-u shortest path is atmost k edges, we can end algorithm after k iterations over edges
Pseudocode:
for each vertex v in vertices:
D[v] := +ooD[s] = 0
repeat k times:
for each edge (u, v) with weight w in edges:
if D[u] + w < D[v]:
D[v] = D[u] + w