首页 > 代码库 > Bellman-Ford
Bellman-Ford
1、对每条边松弛|V|-1次
2、解决单源最短路径问题
3、一般情况,变得权重可以为负
4、时间复杂度O(V*E)
伪码:
BELLMAN-FORD(G,w,S)
INITIALIZE-SINGLE-SOURCR(G,S) 1、初始化所有节点
for i=1 to |G.V|-1 2、进行循环
for each edge(u,v)属于G.E
RELAX(u,v,w) 对每条边都进行一次松弛
for each edge(u,v)属于G.E 3、判断是否存在权值为负的回路
if v.d > u.d+w(u,v)
return FALSE
return TRUE
C++实现
typedef struct Edge{ int src; int dst; int weight; }Edge; int nodenum; int edgenum; int source; const int MAXINT = 9999; const int MAXNUM = 100; Edge edge[MAXNUM]; int dist[MAXNUM]; void init() { cout << "输入节点的个数:"; cin >> nodenum; cout << "输入边的条数:"; cin >> edgenum; cout << "输入源节点的编号:"; cin >> source; for (int i = 1; i <= nodenum; ++i) dist[i] = MAXINT; dist[source] = 0; cout << "输入" << edgenum << "行src dst weight"; for (int i = 1; i <= edgenum; ++i){ cin >> edge[i].src >> edge[i].dst >> edge[i].weight; if (edge[i].src == source){ dist[edge[i].dst] = edge[i].weight; } } } bool bellmanFord() { init(); for (int i = 1; i <= nodenum - 1; ++i){ for (int j = 1; j <= edgenum; ++j){ //relax int u = edge[j].src; int v = edge[j].dst; int weight = edge[j].weight; if (dist[v] > dist[u] + weight) dist[v] = dist[u] + weight; } } for (int i = 1; i <= edgenum; ++i){ //判断是否有负权重值的回路 int u = edge[i].src; int v = edge[i].dst; int weight = edge[i].weight; if (dist[v] > dist[u] + weight) return false; } return true; } int main() { if (bellmanFord()){ for (int i = 1; i <= nodenum; ++i) cout << dist[i] << " "; cout << endl; } system("pause"); return 0; }
《完》
本文出自 “零蛋蛋” 博客,谢绝转载!
Bellman-Ford
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。