本文主要是介绍BellMan-Ford算法--寻找最短路径,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
## 序言 ##
Bellman-Ford算法解决的是一般情况下的单元最短路径问题,在这里,边的权重可以为赋负值,在给定带权重的有向图G=(V,E)和权重函数w:E->,Bellman-Ford 算法返回一个布尔值,以表明是否存在从源节点可以到达的权重为负值的环路。那么如果存在这样一个环路,算法将告诉我们不存在解决方案,如果没有这种环路存在,算法将给出最短路径和它们的权重。
Bellman-Ford 算法通过对边进行松弛操作来逐渐地降低从源节点S到到每个节点v的最短路径的估值v.d,直到该估计值与实际的最短路径权重&(s,v)相同时为止,该算法返回TRUE值当且仅当输入图不包含可以从源节点到达的权重为负值的环路。
## 代码 ##
bool Bellman_Ford()
{for (int i = 1; i <= nodenum; ++i) //初始化dis[i] = (i == original ? 0 : MAX);for (int i = 1; i <= nodenum - 1; ++i)for (int j = 1; j <= edgenum; ++j)if (dis[edge[j].v] > dis[edge[j].u] + edge[j].cost) //松弛(顺序一定不能反~){dis[edge[j].v] = dis[edge[j].u] + edge[j].cost;pre[edge[j].v] = edge[j].u;}bool flag = 1; //判断是否含有负权回路for (int i = 1; i <= edgenum; ++i)if (dis[edge[i].v] > dis[edge[i].u] + edge[i].cost){flag = 0;break;}return flag;
}void print_path(int root) //打印最短路的路径(反向)
{while (root != pre[root]) //前驱{printf("%d-->", root);root = pre[root];}if (root == pre[root])printf("%d\n", root);
}
## 测试程序 ##
#include<iostream>
#include<cstdio>
using namespace std;#define MAX 0x3f3f3f3f
#define N 1010
int nodenum, edgenum, original; //点,边,起点typedef struct Edge //边
{int u, v;int cost;
}Edge;Edge edge[N];
int dis[N], pre[N];bool Bellman_Ford()
{for (int i = 1; i <= nodenum; ++i) //初始化dis[i] = (i == original ? 0 : MAX);for (int i = 1; i <= nodenum - 1; ++i)for (int j = 1; j <= edgenum; ++j)if (dis[edge[j].v] > dis[edge[j].u] + edge[j].cost) //松弛(顺序一定不能反~){dis[edge[j].v] = dis[edge[j].u] + edge[j].cost;pre[edge[j].v] = edge[j].u;}bool flag = 1; //判断是否含有负权回路for (int i = 1; i <= edgenum; ++i)if (dis[edge[i].v] > dis[edge[i].u] + edge[i].cost){flag = 0;break;}return flag;
}void print_path(int root) //打印最短路的路径(反向)
{while (root != pre[root]) //前驱{printf("%d-->", root);root = pre[root];}if (root == pre[root])printf("%d\n", root);
}int main()
{scanf_s("%d%d%d", &nodenum, &edgenum, &original);pre[original] = original;for (int i = 1; i <= edgenum; ++i){scanf_s("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].cost);}if (Bellman_Ford())for (int i = 1; i <= nodenum; ++i) //每个点最短路{printf("%d\n", dis[i]);printf("Path:");print_path(i);}elseprintf("have negative circle\n");return 0;
}
## 程序运行结果 ##
这篇关于BellMan-Ford算法--寻找最短路径的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!