题目描述:
在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?
输入:
输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。输入保证至少存在1条商店到赛场的路线。
当输入为两个0时,输入结束。
输出:
对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间。
样例输入:
1 2 3 4 5 6 7
| 2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
|
样例输出:
图解:
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] dist = new int[n + 1][n + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i == j) { dist[i][j] = 0; } else { dist[i][j] = 10000; } } } for (int i = 1; i <= m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); dist[a][b] = c; dist[b][a] = c; } for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } }
System.out.println(dist[1][n]); } }
|