Q. Does Dijkstra's algorithm work with negative weights?
A. Yes and no. There are two shortest paths algorithms known as Dijkstra's algorithm, depending on whether a vertex can be enqueued on the priority queue more than once. When the weights are nonnegative, the two versions coincide (as no vertex will be enqueued more than once). The version implemented in DijkstraSP.java (which allows a vertex to be enqueued more than once) is correct in the presence of negative edge weights (but no negative cycles) but its running time is exponential in the worst case. (We note that DijkstraSP.java throws an exception if the edge-weighted digraph has an edge with a negative weight, so that a programmer is not surprised by this exponential behavior.) If we modify DijkstraSP.java so that a vertex cannot be enqueued more than once (e.g., using a marked[] array to mark those vertices that have been relaxed), then the algorithm is guaranteed to run in E log V time but it may yield incorrect results when there are edges with negative weights.
上述代码来自https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/DijkstraSP.java.html;
以下摘自知乎:
对于有负权边但无负权回路的图:
1、如果是标准的O(V^2)的Dijkstra,那是算不出的(除非碰巧算对);
2、如果是优先队列优化(或者说堆优化)的版本,也不行(除非碰巧算对);
3、如果是优先队列优化+允许重入队,那么可以(是真的可以计算出来,不是碰巧)。此算法被国内的ACMer称为spfa,但这实际上已经是priority queue-based Bellman-Ford了,是Bellman-Ford算法的变种。(国外好像习惯把这个算法仍旧叫做堆优化的Dijkstra,看作Dijkstra的变种,可能是习惯不一样吧。不过此时已经说不清这到底是Dijkstra还是Bellman-Ford算法了……)
作者:知乎用户
链接:https://www.zhihu.com/question/21620069/answer/24518138
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。