最短路-Bellman-Ford算法
2014-02-12 16:16
274 查看
问题描述
给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。
输入格式
第一行两个整数n, m。
接下来的m行,每行有三个整数u, v, l,表示u到v有一条长度为l的边。
输出格式
共n-1行,第i行表示1号点到i+1号点的最短路。
样例输入
3 3
1 2 -1
2 3 -1
3 1 2
样例输出
-1
-2
数据规模与约定
对于10%的数据,n = 2,m = 2。
对于30%的数据,n <= 5,m <= 10。
对于100%的数据,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保证从任意顶点都能到达其他所有顶点。
View Code
给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。
输入格式
第一行两个整数n, m。
接下来的m行,每行有三个整数u, v, l,表示u到v有一条长度为l的边。
输出格式
共n-1行,第i行表示1号点到i+1号点的最短路。
样例输入
3 3
1 2 -1
2 3 -1
3 1 2
样例输出
-1
-2
数据规模与约定
对于10%的数据,n = 2,m = 2。
对于30%的数据,n <= 5,m <= 10。
对于100%的数据,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保证从任意顶点都能到达其他所有顶点。
#include<iostream> #define MAX 20001 using namespace std; struct edge{ int from, to, cost; }; edge es[200001], e; int d[MAX]; int V, E; int INF = (1 << 30); void shortest_path(int s) { for (int i = 0; i <= V; i++)d[i] = INF; d[s] = 0; bool update; while (true) { update = false; for (int i = 1; i <= E; i++) { 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; } } int main() { cin >> V >> E; for (int i = 1; i <= E; i++) cin >> es[i].from >> es[i].to >> es[i].cost; shortest_path(1); for (int i = 2; i <= V; i++) cout << d[i] << "\n"; system("pause"); return 0; }
View Code
相关文章推荐
- bellman-ford算法 最短路
- 最短路问题 Bellman-Ford算法
- 最短路 bellman-ford算法
- 单源最短路 bellman_ford算法(模板)
- 最短路的Bellman-Ford算法 【判断有无负权环】
- POJ-3259 Wormholes(最短路 Bellman-Ford算法)
- 最短路之Bellman-Ford算法
- POJ - 2240 Arbitrage (最短路 Floyd算法 && Bellman-Ford算法)
- poj 3259 Wormholes(最短路Bellman-Ford算法)
- 蓝桥杯 算法训练 最短路 (Bellman-Ford算法)
- C--最短路(Bellman-Ford算法)
- 最短路——Bellman-ford算法
- 最短路——Bellman-Ford算法
- 单源最短路之bellman-ford算法(解决有负权存在的情况)
- 最短路——Bellman-Ford算法
- 单源最短路之spfa算法代码(bellman-ford算法的队列优化)
- 单源最短路 Bellman-Ford算法
- 2544 最短路 Dijkstra算法 Floyd算法 Bellman_Ford算法 SPFA算法
- poj 1860 Currency Exchange (最短路,Bellman-Ford算法)
- 最短路之Bellman-Ford算法