pq.insert(s, 0.0);
while (!pq.isEmpty()) {
int v = pq.delMin();
for (DirectedEdge e: G.adj(v))
relax(e);
}
...
void relax (DirectedEdge e) {
int v = e.from(), w = e.to();
if(distTo[w] > distTo[v] + e.weight()) {
distTo[w] = distTo[v] + e.weight();
edgeTo[w] = e;
// once a node is newly relaxed, it is inserted to pq,
// meaning that even if a node receives a negative (shorter)
// path late, we won't miss its contribution; pq will still
// dequeue it to relax its adjacent, am I correct?
if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);
else pq.insert(w, distTo[w]);
}
}
那么Dijkstra的算法为什么不能处理负权图?如果通过上述方法使用pq来存储具有distTo值更改的节点,那么它实际上与SPFA algorithm相同,只是SPFA algorithm可以使用FIFO队列而不是优先级队列?< / p>