Spfa Shortest Path

Source: Internet
Author: User

B-F

Applicability

  1. Single-source shortest path (from the source point S to all other vertices V );
  2. Directed Graph & undirected graph (undirected graphs can be seen as Directed Graphs (u, v) and (V, u) that belong to edge set E );
  3. Edge weight can be positive or negative (if an error message is displayed for negative weight loop output );
  4. Differential constraint system;

Algorithm Description
  1. | V |-1 relax (relaxation operation) operation on each edge;
  2. If (u, v) ε E causes dis [u] + W <dis [v], a negative weight loop exists; otherwise, DIS [v] is the shortest distance from S to V, and Pre [v] is the precursor.
For I: = 1 to | v |-1 do // V is the number of vertices for each side (u, v) ε E do // traverse each side relax (U, V, W); For each side (u, v) ε E do if dis [u] + W <dis [v] Then exit (false)

Time-Space complexity

Algorithm time complexity O (VE ). Because the algorithm is simple and widely applied, although the complexity is slightly higher, it is still a very practical algorithm.

 

Algorithm Improvement ---> spfa complexity O (KE), K ≈ 2

 

Algorithm Overview

Spfa (Shortest Path Faster Algorithm) is a queue implementation of the Bellman-Ford algorithm, reducing unnecessary redundant computing. Some people also say that spfa was originally the Bellman-Ford algorithm, and the popular Bellman-Ford algorithm is actually a cottage version.

Algorithm flow

The general process of an algorithm is to use a queue for maintenance. Initially, the source is added to the queue. Each time an element is extracted from the queue and all neighboring points are relaxed (see the final section below). If an adjacent point is relaxed successfully, it is queued.
The algorithm ends when the queue is empty.

This algorithm, simply put, is the Bellman-Ford of queue optimization, which was invented using the features that each vertex does not update too many times.

Spfa -- Shortest Path faster algorithm, which can find the shortest path from the source point to all other points in the time complexity of O (KE) and process the negative edge. The implementation of spfa is even simpler than Dijkstra or bellman_ford:

Set DIST to represent the current shortest distance from S to I, and FA to represent the number of a vertex before I in the current shortest path from S to I. At the beginning, DIST is all + ∞, only Dist [s] = 0, and FA is all 0.

Maintain a queue that stores all vertices that need to be iterated. Initially, the queue only has one vertex S. Use a Boolean array to record whether each vertex is in a queue.

In each iteration, retrieve the vertex v in the head of the team, enumerate the edges V-> U starting from V in sequence, and set the edge length to Len, determine whether Dist [v] + Len is smaller than Dist [u]. If it is smaller than Dist [u], improve Dist [u] and Mark Fa [u] AS v, and because the shortest distance from S to U is smaller,It is possible that u can improve other points, so if u is not in the queue, put it at the end of the team. In this way, the iteration continues until the queue becomes empty, that is, the shortest distance from S to all is determined to end the algorithm. If the number of queues for a vertex is greater than or equal to n, a negative weight ring exists.

The form of spfa is very similar to the width-first search. The difference is that the queue cannot be re-entered when a vertex in the width-first search, however, a point in spfa may be put into the queue again after the queue is out, that is, after a point is improved by another point, it may be improved after a period of time, so it is used again to improve other points, so that iteration continues. Set a vertex to improve other vertices by K on average. It can be proved that K is about 2 in common cases.

 

Array-implemented neighbor table template

# Define n 100004 const int INF = (1 <30); int n, m; // n is the number of the last vertex, struct edge {int U, V, W; int next; // the position where the next edge from the same starting point is stored in the edge array (understand this static adjacent table)} e [N * 10]; int head [N]; // the position where the first edge starting from this point is stored in the E array int dis [N]; // record the bool vis distance from the source point [N]; // record whether the vertex is in the queue. The spfa algorithm can enter the queue multiple times int CNT [N]; // record the number of times the vertex enters the queue int ecnt; void Init () {ecnt = 0; memset (Head,-1, sizeof (head);} void add (int u, int V, int W) {e [ecnt]. U = u; E [ecnt]. V = V; E [ecnt]. W = W; E [ecnt]. Next = head [u]; head [u] = ecnt ++; // location update} bool spfa (INT s) {// s is the source node number queue <int> QQ; int I; for (I = 1; I <= N; ++ I) {dis [I] = inf; // set the distance from other points except the source point to infinity vis [I] = 0; CNT [I] = 0;} dis [s] = 0; // The distance from the source point is 0 vis [s] = 1; CNT [s] ++; // The number of incoming queues at the source point increases by QQ. push (s); int U, V; while (! QQ. Empty () {u = QQ. Front (); QQ. Pop (); vis [u] = 0; for (I = head [u]; I! =-1; I = E [I]. next) {v = E [I]. v; int cost = E [I]. w; If (DIS [v]> Cost + dis [u]) {dis [v] = Cost + dis [u]; If (! Vis [v]) {vis [v] = 1; QQ. push (V); CNT [v] ++; If (CNT [v] >=n) return false ;}}} return true ;}

Vector implements an adjacent table template

# Define n 50001 const int INF = 0x7fffffff; int n, m; typedef struct edge {int to; int W ;}edge, temp; vector <edge> adjmap [N]; // implement the int d [N]; bool vis [N] in the vector adjacent table; // record whether the vertex is in the queue. The spfa algorithm can input the queue multiple times int CNT [N]; // record the number of times the vertex enters the queue void spfa () {queue <int> myqueue; int I; for (I = 2; I <= N; ++ I) d [I] = inf; // set the distance from other points except the source point to infinite memset (VIS, 0, sizeof (VIS); memset (CNT, 0, sizeof (CNT); D [1] = 0; // The distance from the source point is 0 vis [1] = true; CNT [1] ++; // enter the source point Myqueue. Push (1); int topint; while (! Myqueue. empty () {topint = myqueue. front (); myqueue. pop (); vis [topint] = false; for (I = 0; I <adjmap [topint]. size (); ++ I) {int to = adjmap [topint] [I]. to; If (d [topint] <INF & D [to]> d [topint] + adjmap [topint] [I]. w) {d [to] = d [topint] + adjmap [topint] [I]. w; If (! Vis [to]) {vis [to] = true; CNT [to] ++; If (CNT [to]> = N) // when the number of times a node enters the queue is greater than or equal to n, a negative ring is displayed. Return; myqueue. push (to) ;}}} printf ("% d/N", d [N]);} int main () {freopen ("a.txt", "r ", stdin); scanf ("% d", & N, & M); int I; int S, E, W; edge temp; for (I = 1; I <n + 1; ++ I) // clear the adjmap [I] For the adjacent table. clear (); for (I = 0; I <m; ++ I) // bidirectional {CIN> S> E> W; temp. to = E; temp. W = W; adjmap [s]. push_back (temp); temp. to = s; adjmap [e]. push_back (temp);} spfa (); Return 0 ;}


Edition

int map[N][N],dist[N],vis[N];void SPFA(int s){    int i,j;    for(i=0;i<=n;i++){        dist[i] = maxsum;        vis[i] = 0;    }    queue<int> q;    dist[s]=0;    q.push(s);    vis[s]=1;    while(!q.empty()){        int x=q.front();        q.pop();        vis[x]=0;        for(i=1;i<=n;i++){            if(map[x][i] != INF && dist[x]+map[x][i]<dist[i]){                dist[i]=dist[x]+map[x][i];                if(!vis[i]){                    vis[i]=1;                    q.push(i);                }            }        }    }}


If you want to record the shortest path, you need to open an array pre [I]. update pre [J] = I only when dis [I] + map [I] [J] <dis [J]

 

 

 

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.