Shortest Path SPFA algorithm detailed

Source: Internet
Author: User

Shortest Path SPFA algorithm detailed

Scope of application: Given the existence of negative edge of the graph, then similar to Dijkstra and other algorithms will not be used, and the complexity of the bellman-ford algorithm is too high, SPFA algorithm will be useful. We agree that there is no negative right loop for the weighted graph G, that is, the shortest path must exist. Of course, we can do a topological sort before executing the algorithm to determine if there is a negative power loop, but this is not the focus of our discussion.


Algorithm idea: We use the array D to record the shortest path estimate for each node, and use the adjacency table to store the graph G. The approach we take is dynamic approximation: Set up a FIFO queue to hold the nodes to be optimized, optimize each time you remove the first node of the team, and use the current shortest path estimate of the U point to relax the node v pointed at the left U point, and if the shortest path estimate of the V point is adjusted, And the V point is not in the current queue, the V point is placed in the tail of the team. This keeps the nodes out of the queue for relaxation until the queue is empty.

The expected time complexity O (ke), where k is the average number of incoming teams for all vertices, can prove that K is generally less than or equal to 2.

Implementation method:

Set up a queue that initially has only a starting point in the queue, and then establish a table that records the shortest path from the starting point to all points (the initial value of the table is assigned a maximum value, and the point to his own path is assigned to 0). Then perform the slack operation, use the point in the queue as the starting point to flush to the shortest point of all points, if the refresh is successful and the refresh point is not in the queue then add that point to the queue at the end. Repeated execution until the queue is empty.

To determine whether there is a negative ring:
A negative ring exists if a point enters the queue more than n times (SPFA cannot process a graph with negative loops)


First establish the shortest path table for the starting point A to the remaining points



First the source point A is queued when the queue is non-empty:
1, team first element (a) out of the team, the end of all edges with a as the starting point of the relaxation operation (here b,c,d three points), the path table status is:


The shortest path valuations of the three points are smaller at the time of relaxation, and none of these points are present in the queue, which
Need to queue up, at this time, new queued three nodes B,c,d

The team first element B points out of the team, the end of all the edges with B as the starting point of the relaxation operation (here only the e point), the Path table status is:



In the Shortest path table, the shortest path value of E is also smaller, E does not exist in the queue, so E also
The element in the queue is C,d,e

The first element of the team C points out of the team, the end of all the edges with C as the starting point of the relaxation operation (here is e,f two points), the path table status is:



In the Shortest path table, the shortest path estimate for e,f is smaller, e exists in the queue, and F does not exist. So
e do not queue up, F to team, this time the elements in the queues are d,e,f

The first element of the team D points out of the team, the end of all the edges with D as the starting point of the relaxation operation (here only g this point), at this time the path table state is:



The first element of the team is e,f,g. Then e points out to the team, E only points to G, and then at this point the shortest path of G is not smaller (slack is not successful), no new nodes are queued, the elements in the queue are f,g, the table state is still:



The first element of the team F points out of the team, the end of all the edges with F as the starting point of the relaxation operation (here is d,e,g three points), the path table status is:



In the Shortest path table, the shortest path estimation of the e,g is smaller, there is no e point in the queue, E queue, there is g this point in the queues, G does not queue, the element in the queues is G,e

The first element of the team G points out of the team, the end of all the edges with G as the starting point of the relaxation operation (here only point B), the Path table status is:



In the Shortest path table, the shortest path value of B is smaller, there is no B point in the queue, B is queued, and the element in the queue is E,b
The first element of the team e points out of the team, the end of all the edges with E as the starting point of the relaxation operation (here only g this point), at this time the path table state is:


In the Shortest path table, the shortest path value of G does not change (slack is unsuccessful), when the element in the queue is B

The team first element B points out of the team, the end of all the edges with B as the starting point of the relaxation operation (here only the point of e), the Path table status is:



In the Shortest path table, the shortest path value of E is not changed (slack is unsuccessful) and the queue is empty

The shortest path to the final A to G is 14.


Note: The theoretical part is reproduced, the code is original.


#include <iostream> #include <deque> #include <cstdio> #include <algorithm>using namespace std; const int MAXN = 110;const int MAXM = 10100;const int INF = 0x3f3f3f3f;struct edge{int from, to, cap, next;}; Edge edge[maxm];int head[maxn];int path[maxn];int inqueue[maxn];int dist[maxn];int viscnt[maxn];int cnt;void Addedge ( int from, int. to, int cap) {Edge[cnt].from = From;edge[cnt].to = To;edge[cnt].cap = Cap;edge[cnt].next = Head[from];head[f ROM] = cnt++;} int relax (int u,int v,int c) {if (Dist[u] + C < dist[v]) {Dist[v] = Dist[u] + c;return 1;} return 0;} BOOL SPFA (int src, int n) {deque<int> dq;memset (viscnt, 0, sizeof viscnt); memset (inqueue, 0, sizeof inqueue); me Mset (Dist, INF, sizeof Dist), memset (Path,-1, sizeof path); INQUEUE[SRC] = 1;viscnt[src]++;d ist[src] = 0;dq.push_back ( SRC); while (!dq.empty ()) {int u = dq.front ();d q.pop_front (); Inqueue[u] = 0;for (int i = head[u]; I! =-1; i = edge[i].next) {int v = edge[i].to;if (Dist[u] < Inf&&relax (U, V, Edge[i].cap)) {Path[v] = u;if (!inqueue[v]) {Inqueue[v] = 1;viscnt[v]++;if (viscnt[v] = = N) return false;if (!dq.empty () & amp;& Dist[v] <= Dist[dq.front ()]) Dq.push_front (v); Elsedq.push_back (v);}}} return true;}  int main () {int n,m;while (CIN >> n >> m &&n&&m) {memset (head,-1, sizeof head); cnt = 0;for (int i = 1; I <= m; i++) {int A, B, C;cin >> a >> b >> C;addedge (A, B, c);//Add an edge Addedge (b, A, c) in a->b with a load of C;} SPFA (1, n); cout << dist[n] << Endl;} return 0;}


Shortest Path SPFA algorithm detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.