Bellman-Ford算法的实现
来源:互联网 发布:冷艳锯 知乎 编辑:程序博客网 时间:2024/05/18 01:57
参照了紫书,同时要注意存储相应的信息,打印的时候进行逆向打印即可,具体实现见如下代码:
#include<iostream>#include<vector>#include<string>#include<set>#include<stack>#include<queue>#include<map>#include<algorithm>#include<cmath>#include<iomanip>#include<cstring>#include<sstream>#include<cstdio>#include<deque>#include<functional>using namespace std;class Edge{public:int x, y, w;};class Graph{public:int n, m;//顶点和边vector<Edge> edge;vector<int> G[1005];int parent[1005];int dist[1005];int amount[1005];const int Inf = 0x3f3f3f3f;int inq[1005];void Init(){cin >> n >> m;for (int i = 0; i < m; i++){Edge temp;cin >> temp.x >> temp.y >> temp.w;edge.push_back(temp);G[temp.x].push_back(edge.size()-1);//边的编号从0开始}memset(inq,0,sizeof(inq));memset(dist,Inf,sizeof(dist));memset(amount, 0, sizeof(amount));memset(parent,-1,sizeof(parent));}void Print(int i){cout << "result:" << endl;for (int j = 2; j <= n; j++){cout << j << ": ";if (dist[j] == Inf){cout << "does not exist" << endl;continue;}cout <<"length: "<< dist[j] << " : ";vector<int> res;int k = j;res.push_back(k);while (parent[k] != -1){int ide = parent[k];res.push_back(edge[ide].x);k = edge[ide].x;}reverse(res.begin(),res.end());for (int t = 0; t < res.size(); t++){cout << res[t] << " ";}cout << endl;}}void Deal(int i){Init();dist[i] = 0;queue<int> q;q.push(i);inq[i] = true;while (!q.empty()){int id = q.front();inq[id] = false;q.pop();for (int j = 0; j < G[id].size(); j++){int ide = G[id][j];int from = edge[ide].x;int to = edge[ide].y;if (dist[from] == Inf) continue;if (dist[to] > dist[from] + edge[ide].w){dist[to] = dist[from] + edge[ide].w;parent[to] = ide;if (!inq[to]){amount[to]++;if (amount[to] >= n){cout << "Error" << endl;return;}inq[to] = true;q.push(to);}}}}Print(i);return;}};int main(){Graph a;a.Deal(1);system("pause");return 0;}/*5 71 2 42 3 61 5 11 4 -85 4 -32 4 -24 3 -104 41 2 -12 3 23 4 34 1 -100*/
阅读全文
0 0
- Bellman-Ford算法的实现
- Bellman-ford算法实现
- Bellman-Ford算法实现
- Bellman-Ford算法实现类
- Bellman-Ford算法实现小结
- Bellman-Ford算法 的认识
- Bellman-Ford算法的详解
- 求任意权值最短路径的Bellman-Ford算法实现
- C++算法实现Bellman-Ford算法
- Java C 实现Bellman-ford算法
- Bellman-Ford 算法实现单源最短路径
- POJ3259—Bellman-Ford算法实现
- Bellman-Ford贝尔曼福特算法实现
- bellman-ford算法的优化spfa算法
- Bellman-Ford算法的改进:SPFA算法
- 求单源最短路径的算法(Bellman-Ford)
- poj_1860 Bellman-Ford算法的逆向应用
- Bellman-Ford判断有负环的算法模板
- 股票量化分析(12)——第三个策略(kdj策略)
- 腾讯2016研发工程师编程题(一)----[编程题] 生成格雷码
- Redis 数据库架构
- FastDFS详细安装步骤,测试;Nginx中配置FastDFS,并提供优化,下载方法,楼主已测
- 文章标题 AngularJs表单验证
- Bellman-Ford算法的实现
- 软件推荐
- Spark SQL Catalyst深入理解
- LeetCode-114. Flatten Binary Tree to Linked List
- display:table的用法
- 股票利益最大化
- Github综合
- 大话设计模式----工厂模式
- 自考总结-2017.10.22