Several algorithms for the shortest path

Source: Internet
Author: User

There are several algorithms for the shortest Dijkstra,bellman-ford,floyd.

Dijkstra:

The Dijkstra is suitable for cases where the right edge is positive, from a single source point to the shortest path to all other nodes.

The core of the algorithm is to update the distance from the node I already know d[i] to the other nodes connected to the node.

voidDijkstra () {memset (Vis,0,sizeof(VIS));//The Vis array indicates whether the node is accessed.memset (D,inf,sizeof(d));//the D array represents the distance to the node.d[s]=0;//set the distance of the starting point to 0     for(intI=1; i<=n;i++)    {        inttmp,minn=INF;  for(intj=1; j<=n;i++)        {            if(!vis[j] && d[j]<Minn) {Minn=D[j]; TMP=J; }        }                            //Find a node with the smallest distance in all the points that have been asked to visitvis[tmp]=1;  for(intj=1; j<=n;j++)            if(d[tmp]+w[tmp][j]<D[j]) d[j]=D[TMP]+W[TMP][J];//The distance from the node to be updated and connected with the smallest node .    }}

This way the N nodes are updated to get the distance from the starting point to the other nodes, the complexity of which is O (n^2)

But sometimes the edges are not so much a sparse graph that they can be optimized with priority queuing to O (MLOGN)

structedge{int  from, To,dis; Edge (intUintVintD): from(U), to (v), dis (d) {}};structnode{intD,u;//d is the distance, and U is the number of another node.    BOOL operator< (ConstNode A)Const    {        returnD>A.D; }};vector<Edge>Edges;vector<int>G[MAXN];intVIS[MAXN];//determine if the node is being accessed.intP[MAXN];//an arc in the shortest wayintD[MAXN];//The distance from the beginning s to each pointvoidDijkstra () {priority_queue<node>Q; memset (Vis,0,sizeof(VIS));  for(intI=1; i<=n;i++) D[i]=INF; D[s]=0;    node start; START.D=0, start.u=s;    Q.push (start);  while(!Q.empty ()) {node x=Q.top;        Q.pop (); intu=x.u; if(Vis[u])Continue; Vis[u]=1;  for(ITN i=0; I<g[u].size (); i++) {Edge& e=Edges[g[u][i]]; if(d[e.to]>d[u]+E.dis) {node Next; D[e.to]=d[u]+E.dis; P[e.to]=G[u][i]; NEXT.D=D[e.to]; Next.u=e.to;            Q.push (next); }        }    }}

The core of the idea is still unchanged, is still used to know the point to update the starting point S to other points of distance, with priority queue, the highest priority is the distance of the smallest point, and then use this point to update other points

The worst case is still looping n-1 times, but on the whole, each edge is checked once, so the slack operation happens to be an M-time, so that only the minimum value of the inaccessible D can be found.

It can be said that even the dense graph, using the priority_queue or the adjacency matrix Dijstra algorithm faster, because the D[e.to]>d[u]+e.dis can not meet the queue, all push operations will be very few

Bellman-ford:

Bellman-ford is also a short-circuit algorithm, the algorithm used to calculate the shortest possible time, if the shortest circuit exists, then must be a non-ring of the shortest, then this algorithm has a useful is to judge the ring,

If there is a negative ring, then there will be no shortest path (because it will continue to relax)

If the ring is not included, then the maximum through the N-1 node (not including the starting point), through the n-1 relaxation operation can calculate the shortest

The core of the algorithm is to update the node distance by the loop n-1 time, and each time the edge is relaxed and operated .

 for(intI=1; i<=n;i++) D[i]=inf;d[0]=0; for(intI=0; i<n-1; i++)//iterative n-1 Times{     for(intj=0; j<m;j++)//Check each edge    {        intx=u[i],y=V[i]; if(d[x]<INF) {D[y]=min (D[y],d[x]+w[i]);//Slack Operation        }    }}

This code is obviously not a negative ring to determine, the complexity is O (nm)

Can be optimized with FIFO queues for loop checking

structedge{int  from, To,dis; Edge (intUintVintD): from(U), to (v), dis (d) {}};vector<Edge>Edges;vector<int>G[MAXN];intVIS[MAXN];//determine if the node is being accessed.intP[MAXN];//an arc in the shortest wayintD[MAXN];//The distance from the beginning s to each pointBOOLBellman-ford (ints) {Queue<int>Q; memset (INQ,0,sizeof(INQ)); memset (CNT,0,sizeof(CNT));  for(intI=0; i<n;i++) D[i]=INF; D[s]=0; Inq[s]=true;    Q.push (s);  while(!Q.empty ()) {        intu=Q.front ();        Q.pop (); Inq[u]=false;  for(intI=0; I<g[u].size (); i++) {Edge& e=edges (g[u][i]); if(D[u]<inf && D[e.to]>d[u]+e.dis)//Slack{d[e.to]=d[u]+E.dis; P[e.to]=G[u][i]; if(!Inq[e.to])                    {Q.push (e.to); Inq[e.to]=true; if(++cnt[e.to]>n)return false;//If a point is enqueued more than n times, then there must be a negative ring                }            }        }        return true; }}

Queue-Optimized Bellman-ford also called SPFA (shortest Path Faster algorithm)

Below is a discussion of SPFA

First reprint these two articles, think write good, later slowly pits

http://blog.csdn.net/hqd_acm/article/details/5442872

http://blog.csdn.net/hqd_acm/article/details/5804345

Several algorithms for the shortest path

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.