Unit Shortest Path Algorithm template summary (Dijkstra, BF,SPFA), with chain-forward star template

Source: Internet
Author: User

One: Dijkstra algorithm
Time complexity, with priority queue optimization, O ((m+n) Logn)
The shortest path of single source requires that the weights of all sides are not negative. If the weighted value is negative in the graph, the Dijkstra algorithm will fail, and the shortest path can be wrong.

Road[i][j] represents the adjacent I-to-J Road length
The U-set stores the nodes that have been evaluated to the shortest path to the source point, and the S collection represents the nodes that have not yet been evaluated
Dis[i] represents the shortest path from I to the source node (set to 0)
Vis[i]=1 represents the I node in the U set

Just started dis[0]=0,vis[0]=1;dis[i]=maxn,vis[i]=0;
For 1 to N:
1: Find the smallest node of dis[] from the s set
Remove I from S and insert into u, i.e. vis[i]=1;
2: Traverse all nodes adjacent to I J
If DIS[I]+ROAD[I][J]<DIS[J]
Then Dis[j]=dis[i]+road[i][j];
3: Ext. 1

//find the shortest path of other points to source s and optimize with priority queueintROAD[MAXN][MAXN];//Road[i][j] Represents the distance between I and J (this refers to the time that the route was entered)intDIS[MAXN];//Dis[i] Indicates the shortest path size of the I point to the source point sintVIS[MAXN];//vis[i]=1 indicates that node I has already obtained a single source shortest path to the source pointvector<int> LINK[MAXN];//Link[i] Indicates which points I connect withintn,m;structnode{intU,dis;//u: node dis: Distance to source point s    BOOL operator< (ConstNode tmp)Const{        returndis>tmp.dis;//The default priority sequence is "maximum", which is the first to be taken out. So here's the big to the small sort    }};voidDijkstra () {priority_queue<Node>Q;    Node Tmp,a;  for(intI=0; i<maxn;i++) Dis[i]=INF; memset (Vis,0,sizeof(VIS)); Dis[s]=0; A.dis=0; A.U=s;    Q.push (a);  while(!Q.empty ()) {tmp=Q.top ();        Q.pop (); intidx=tmp.u; VIS[IDX]=1;  for(intk=0; K<link[idx].size (); k++) {            intv=Link[idx][k]; if(!Vis[v]) {                if(dis[idx]+road[idx][v]<Dis[v]) {Dis[v]=dis[idx]+Road[idx][v]; A.dis=Dis[v]; A.U=v;                Q.push (a); }            }        }    }}
View Code

Two: Bellman-ford algorithm
Adjacency Matrix: O (v^3) adjacency table: O (VE)
The Bellman-ford algorithm can solve the problem of shortest path of single source point under more common conditions (existence of negative weights).
If there is a negative weight loop, the algorithm returns a value of false, indicating that the shortest path does not exist. (The negative weight loop means that the weight of the loop and is negative)

Why does the BF algorithm need to n-1 iteration? This is because "if there is a shortest path between two points, then each node passes at most once." That is to say, this road does not exceed the n-1 edge. "
Because if a node passes two times, then we walk a circle. If the power of this circle is positive, it is obviously not cost-effective, if the negative circle, then the shortest circuit does not exist, if 0 laps, the removal does not affect the optimal value.

Many times, the number of iterations needed to get the best value is much smaller than V-1. Therefore, in the iterative process, you can add a judgment, if you find that the shortest path estimates of all the nodes are not updated, you can exit.

//finding the shortest path from the source point s to each nodeBOOLBellman_ford (ints) {    //Initialize     for(intI=0; i<n;i++) {Dist[i]=inf;//I to the source point s distancepre[i]=-1;//the precursor node of I, used for the output path} Dist[s]=0;  for(intI=1; i<n;i++) {//Perform n-1 iterations         for(Each (u,v) ∈e) {//relax once for all sides            if(dist[u]+w[u][v]<Dist[v]) {Dist[v]=dist[u]+W[u][v]; PRE[V]=u; }        }    }    //If a n-1 iteration is performed, there is still a path that can be updated, indicating that there is a negative weight loop that returns false     for(each (u,v) ∈e) {if(dist[u]+w[u][v]<Dist[v]) {            return false; }    }    return true;}
View Code

Three: SPFA (shortest Path Faster algorithm)

Time complexity: O (KE), K is generally less than or equal to 2. But the SPFA algorithm is not stable, that is, for some special data, K may be larger.

is based on the BF, the use of queue optimization, the approximate process of the algorithm is to use a queue for maintenance. Initially, the source is added to the queue,

Each time an element is taken out of the queue, and all points adjacent to him are relaxed, and if an adjacent point relaxes successfully, it is enqueued. The algorithm ends until the queue is empty.


If there is a negative-weight loop, you need to create a count array that returns when the number of points is more than V (the number of vertices).

intVis[i]://used to mark whether the point I is in the queue//calculates the shortest short-circuit length of the source point S to each node, where it traverses the adjacent linked list-the chain forward starvoidSPFA (ints) {Queue<int>Q; intu,v; Dist[s]=0;    Q.push (s); Vis[s]=1;  while(!Q.empty ()) {u=Q.front ();        Q.pop (); Vis[u]=0; //The end of all the out edges of u is relaxed, and if you can make the path of source point to V shorter by U, update         for(intk=head[u];k!=-1; k=Edge[k].next) {v=edge[k].to; if(dist[u]+w[u][v]<Dist[v]) {Dist[v]=dist[u]+W[u][v]; //Add to queue if Point V is not in queue                if(!Vis[v])                    {Q.push (v); VIS[V]=1; }            }        }    }}
View Code

The following is a template for the chain forward star:

//adjacency linked list storage-chain forward star//Head[i]: The ordinal of the last edge of the parent node I that points to the child node I was connected to//Edge[k].next: The number of an adjacent edge that represents an edge numbered K, and the two edges are drawn from the same node//edge[k].to: Represents the node number pointed to by an edge numbered K//int head[n],tot;//N is the number of vertices, and M is the number of edgesstructedge{intNext,to;} EDGE[M]voidAddintXinty) {Edge[tot].next=Head[x]; Edge[tot].to=y; HEAD[X]= tot++;}//Initializevoidinit () {memset (head,-1,sizeof(head)) tot=0;}//Traverse all points adjacent to X v for(intK = head[x];k!=-1; k=Edge[k].next) {    intv =edge[k].to; //...}
View Code

Unit Shortest Path Algorithm template summary (Dijkstra, BF,SPFA), with chain-forward star template

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.