最短路 bellman-ford算法
2014-05-27 14:17
281 查看
问题描述 给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。 输入格式 第一行两个整数n, m。 接下来的m行,每行有三个整数u, v, l,表示u到v有一条长度为l的边。 输出格式 共n-1行,第i行表示1号点到i+1号点的最短路。 样例输入 3 31 2 -12 3 -13 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
package job525; import java.util.Scanner; class Eage{ int from; int to; int cost; public int getFrom() { return from; } public void setFrom(int from) { this.from = from; } public int getTo() { return to; } public void setTo(int to) { this.to = to; } public int getCost() { return cost; } public void setCost(int cost) { this.cost = cost; } public Eage(int from,int to,int cost) { this.from = from; this.to = to; this.cost = cost; } } public class 最短路bellman_ford { static int m,n,inf=100000;//n:n个顶点;m:m条边 static int []d=new int[20000]; static Eage []eg=new Eage[200000]; public static void main(String[] args) { Scanner sc=new Scanner(System.in); n=sc.nextInt();m=sc.nextInt(); int i=0; while(i<m) { int u, v, l; u=sc.nextInt(); v=sc.nextInt(); l=sc.nextInt(); eg[i++]=new Eage(u,v,l); } //测试存储--------------------------------------------------------------------------------- /* for(i=0;i<m;i++) { System.out.println("("+eg[i].getFrom()+","+eg[i].getTo()+"):"+eg[i].getCost()); } */ //测试结束---------------------------------------------------------------------------------- bellman_ford(); for(i=2;i<=n;i++) { System.out.println(d[i]); } } public static void bellman_ford() { init(); while(true) { boolean flag=false; for(int i=0;i<m;i++) { Eage e=eg[i]; if(d[e.getFrom()]!=inf&&d[e.getTo()]>d[e.getFrom()]+e.getCost()) { d[e.getTo()]=d[e.getFrom()]+e.getCost(); //System.out.println("("+eg[i].getFrom()+","+eg[i].getTo()+"):"+eg[i].getCost()+d[e.getTo()]);//测试 flag=true; } } if(!flag) break; } } public static void init() { for(int i=1;i<=n;i++) d[i]=inf; d[1]=0; } }
View Code
相关文章推荐
- POJ - 2240 Arbitrage (最短路 Floyd算法 && Bellman-Ford算法)
- POJ-3259 Wormholes(最短路 Bellman-Ford算法)
- 最短路之Bellman-Ford算法
- C--最短路(Bellman-Ford算法)
- 最短路——Bellman-ford算法
- poj 3259 Wormholes(最短路Bellman-Ford算法)
- 蓝桥杯 算法训练 最短路 (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算法)
- ACM暑期集训——专题二[最短路Bellman-Ford算法]
- 最小费用流模板(Bellman-Ford算法找最短路)
- 求最短路之Bellman-Ford算法
- poj1860 【最短路&&bellman_ford算法】
- hdu 2544 最短路 (Bellman_Ford算法)