﻿ 负权重使用Dijkstra的算法 - 代码日志

#### 负权重使用Dijkstra的算法

``````    2
A-------B
\     /
3 \   / -2
\ /
C
``````

Assuming the edges are all directed from left to right, If we start
with A, Dijkstra’s algorithm will choose the edge (A,x) minimizing
d(A,A)+length(edge), namely (A,B). It then sets d(A,B)=2 and chooses
another edge (y,C) minimizing d(A,y)+d(y,C); the only choice is (A,C)
and it sets d(A,C)=3. But it never finds the shortest path from A to
B, via C, with total length 1.

``````Dijkstra(G, w, s)  {
Initialize-Single-Source(G, s)
S ← Ø
Q ← V[G]//priority queue by d[v]
while Q ≠ Ø do
u ← Extract-Min(Q)
S ← S U {u}
for each vertex v in Adj[u] do
Relax(u, v)
}

Initialize-Single-Source(G, s) {
for each vertex v  V(G)
d[v] ← ∞
π[v] ← NIL
d[s] ← 0
}

Relax(u, v) {
//update only if we found a strictly shortest path
if d[v] > d[u] + w(u,v)
d[v] ← d[u] + w(u,v)
π[v] ← u
Update(Q, v)
}
``````

Meir

>首先，将d(A)设置为零，将其他距离设置为无穷大。
>然后展开节点A，将d(B)设置为1，将d(C)设置为零，将d(D)设置为99。
>接下来，展开C，没有净变化。
>然后展开B，这没有效果。
>最后，展开D，将d(B)更改为-201。

http://stackoverflow.com/questions/6799172/negative-weights-using-dijkstras-algorithm