Bellmanford 最短路(1)

来源:互联网 发布:ubuntu好用的输入法 编辑:程序博客网 时间:2024/06/04 23:35

Bellman-Ford算法


1.单源最短路
2.可处理包含负值的环路
3.效率O(V*E)
4.有向图无向图均适用
5.该文代码图采用邻接表形式储存

原理:

当我们寻找一条最短路时,假设源节点2可以到达的节点v,设p=<\v0,\v1,\v2,\v3,\v4>为最短路,则最短路径包含4-1=3条边,我们在操作中松弛了每条边。第i次松弛我们则找到<\V*i-1*,\Vi>条路。所以我们只要对E条边分别进行V-1次操作即可

#include<iostream>#define MAX_E 10001#define MAX_V 1001#define INF 0x3f3f3f3f  using namespace std;struct edge{    int from;    int to;    int cost;};//int d[MAX_V];//distanceint V,E;//the number of Vertex,Edgeedge es[MAX_E];//Edges//int pre[MAX_V];//mark the pre vertex;bool Bellmanford(int s){    for(int i=0;i<=V;i++){d[i]=INF;}    d[s]=0;    for(int i=0;i<V-1;i++){        for(int j=0;j<E;j++){            if(d[es[j].to]>d[es[j].from]+es[j].cost){                d[es[j].to]=d[es[j].from]+es[j].cost;            }        }    }    bool flag=true;    for(int i=0;i<V-1;i++){        for(int j=0;j<E;j++){            if(d[es[j].to]>d[es[j].from]+es[j].cost){                flag=false;            }        }    }    return flag;}int main(){    V=4;    E=5;    es[0].from=1;    es[0].to=2;    es[0].cost=1;    es[1].from=1;    es[1].to=3;    es[1].cost=3;    es[2].from=1;    es[2].to=4;    es[2].cost=5;    es[3].from=2;    es[3].to=4;    es[3].cost=2;    es[4].from=3;    es[4].to=4;    es[4].cost=4;    if(Bellmanford(1)){        for(int i=1;i<=4;i++){            cout<<d[i]<<" ";        }    }    else{        cout<<"There exits the loop"<<endl;    }}
0 0