Bellman-ford algorithm is a single source shortest path algorithm, which allows negative edge in the graph. The Bellman-ford algorithm is relatively inefficient, but it is easy to write and well understood. The more popular SPFA algorithm is actually his queue optimization. The flow of the Bellman-ford algorithm is generally the case, first set the shortest path of the source point to 0, the other node's shortest path is set to INF, and then the n-1 iteration, each check each edge for relaxation operation, so that the other nodes are the shortest. And can check whether there is a negative ring, if the N iterations can still be relaxed operation, then there is a negative ring. It is not difficult to see that the complexity of time is O (nm). How do you understand the Bellman-ford algorithm? Think of a shortest path tree, the root is the source point, the leaf node is the other nodes in the diagram, the leaf node to the root of the path of the node is the shortest point of other nodes. Although we didn't know what to look like at the beginning of the tree, he was an objective reality. And the Bellman-ford algorithm is layered structure of the shortest-path tree, assuming that the first layer of processing, then the first layer of i-1 has been processed, then scan each edge, see if it can be relaxed, it can be extended from the I-1 layer to layer I. If the source point is considered as the No. 0 layer, then the tree has a maximum of n-1 layer, so the iterative n-1 times must be able to get the shortest possible tree (if present), then if the nth time can still be relaxed operation, indicating that there is no shortest path (existence of negative ring).
1#include <cstdio>2#include <cctype>3#include <cstring>4 Const intinf=0x3f3f3f3f;5 intN,M,S,D[MAXN];6 structEdge {7 intu,v,w;8Edgeintu=0,intv=0,intw=-1): U (U), V (v), W (w) {}9 } E[MAXM];Ten BOOLBellman () { Onememset (D,inf,sizeof(d)); Ad[s]=0; - for(intI=1; i<=n;++i)//loop check n times, normally up to iterative n-1 times, nth time to determine if there is a shortest path - for(intI=1; i<=m;++i) { the intu=e[i].u,v=e[i].v,w=E[I].W; - if(D[V]>D[U]+W) {//Slack Operation - if(i==n)return false; - Elsed[v]=d[u]+W; + } - } + return true; A } at intMain () { -scanf"%d%d%d",&n,&m,&s); - intu,v,w; - for(intI=1; i<=m;++i) { -scanf"%d%d%d",&u,&v,&W); -e[i]=Edge (u,v,w); in } - if(!bellman ()) printf ("wrong!"); to Else for(intI=1; i<=n;++i) { + if(i!=1) Putchar (' '); -printf"%d", D[i]); the } * return 0; $}
Bellman-ford algorithm