MissSirius
MissSirius

Reputation: 387

How to Find shortest paths with k negative weighted edges?

The problem is to find shortest paths from a start vertice to all other vertices in a directed graph.

But the graph will have m positive weighted edges and k negative weighted edges, and it's guaranteed that negative weighted edges will be not in a cycle. In other words, there is no negative weighted cycle in this graph.

I tried to directly use Bellman-Ford and SPFA to solve this question but does there exists a faster way to do this?

Upvotes: 3

Views: 1148

Answers (1)

David Eisenstat
David Eisenstat

Reputation: 65468

If k is large enough, you should probably just run Bellman–Ford and call it a day.

If k is small, you can borrow the re-weighting trick from Johnson’s algorithm, but with a faster initialization than just running Bellman–Ford. Recall that Johnson computes a potential π(v) for each vertex and adjusts the cost of each arc vw from c(vw) to c′(vw) = c(vw) − π(v) + π(w), choosing π so that c′ is nowhere negative. The shortest path between s and t is the same with respect to c as with respect to c′,

Suppose that the input graph G has exactly one negative arc, let’s say c(xy) < 0. Use Dijkstra’s algorithm to compute distances in G − xy from y to all other vertices. Then define π(v) = distance(y, v). The correctness proof follows the proof of Johnson’s algorithm; the arc xy can’t be part of a shortest path from y because there are no negative cycles, so Dijkstra on G - xy in fact computes a shortest path tree for G.

For general k, we can do this recursively. If k = 0, run Dijkstra. Otherwise, remove a negative arc and compute shortest paths recursively instead of with Dijkstra. Once we have good values for π, run Dijkstra one more time, from the given start vertex.

The overall running time is O((k + 1) (m + n log n)) with Fibonacci heaps.

Upvotes: 3

Related Questions