单源最短路问题BellMan-Ford算法C++实现关键代码

来源:互联网 发布:单片机plc哪个好学 编辑:程序博客网 时间:2024/04/30 14:59

Bellman-Ford算法,使用于两点间的最短距离计算,存在负边时也可以计算。

复杂度为:O(|V|*|E|)(边的数目乘以点的数目)

基本思想如下:先计算一条边时的最短距离,然后计算2条时最短距离,一直到最短距离不再更新(最大不超过E-1[E为边的数目])

记从起点s出发到顶点i的最短距离为d[i],则下式成立

d[i]=min{d[j]+(从j到i的距离的权值|e=(j,i)∈E)}

设初值的d[s]=0,d[i]=INF(足够大常数),再不断利用上述规则更新即可。

关键C++源码如下

//从顶点from指向定点to的权值为cost的边struct edge{int from,to,cost;};edge es[MAX_E];//edgeint d[MAX_V];//the shortest distenceint V,E;//V is the number of voltage,E is the number of edge//求解从顶点s出发到所有点的最短距离void shortest_path(int s){    for(int i=0;i<V;i++) d[i]=INF;    d[s]=0;    while(true)    {        bool update =false;        for(int i=0;i<E;i++)        {            edge e =es[i];            if(d[e.from ]!=INF&&d[e.to]>d[e.from]+e.cost)            {                d[e.to]=d[e.from]+e.cost;                update =true;            }        }        if(!update) break;    }}





0 0
原创粉丝点击