Bellman-Ford
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章