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]);
}
}
So why can Dijkstra's algorithm not handle negative-weight graph? If it's implemented in the above way that uses a pq to store the nodes that has distTo value change, is it actually the same as the SPFA algorithm except that SPFA algorithm may use FIFO queue instead of priority queue?