Thoughts on Dijkstra and SPFA

In fact, writing heap-optimized Dijstra on a graph without negative edges is the same as heap-optimized SPFA, so I went back and reconsidered why SPFA can only be used to judge negative rings.

When heap optimization is not considered, Dijstra and SPFA are actually two ideas.

Dijstra has a greedy mind, which is similar to Prime. Dijstra not only cannot judge negative rings, it cannot be used for graphs with negative edges. So on a graph without negative edges, first find the point v closest to the starting point through the edge e of the starting point. The shortest distance from this v to the starting point must be the edge weight of e. Going from another point to v must not go directly to v. Then use the nearest point v to update the distance from the starting point to other points, mark this point as having an answer , and repeat the above process. If once there is a negative edge, such as a to b distance of 3, a to c distance of 5, c to b distance -4, then obviously the shortest distance from a to b is 1, and we have marked the shortest of b in the first step The distance is 2, obviously Dijstra "wrong". It may be said that we do not mark that every point has an answer, but this becomes the Bellman-Ford algorithm.

SPFA comes from Bellman-Ford and is based on iterative thinking. I scan each edge and use each edge to update the values ​​from the starting point to the other points. If the update is successful, the updated point may be used as a transit point to reduce the distance from the starting point to other points, so all the edges of the updated point are used to update the distance from the starting point to other points. For convenience, we put these updated points into the queue, which becomes SPFA. In SPFA, we will not mark a point where the current answer is the final answer, and the algorithm ending condition is that the queue is empty. Therefore, on a graph with negative weights, SPFA seeking the shortest path is not affected.

Dijstra can no longer execute on graphs with negative edges, let alone graphs with negative rings. So, how does SPFA judge a negative ring?

On a graph without negative loops, the path between any two points is a line, and no loops will appear. This conclusion is obvious. Any sum of the edges on the ring is positive, so it is better not to have it. The path of a line passes through at most n points and has n-1 edges, so obviously the number of points passed from the starting point to any point does not exceed the total number of points on the graph n. Then every time there is an updated point in SPFA, we record how many points have passed on the shortest path from the starting point to this point. Once it exceeds n, it means that there is a negative ring.

 

Guess you like

Origin blog.csdn.net/Luowaterbi/article/details/112693526