Design an algorithm for the single source shortest path problem that runs in time O(k(|V|+|E|))

前端 未结 1 617
悲&欢浪女
悲&欢浪女 2021-01-20 02:43

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

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 02:58

    Here`s O(k(|V | + |E|)) approach:

    1. We can use Bellman-Ford algorithm with some modifications
    2. Create array D[] to store shortest path from node s to some node u
    3. initially D[s]=0, and all other D[i]=+oo (infinity)
    4. 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
    5. 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] := +oo

      D[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

    0 讨论(0)
提交回复
热议问题