就很普通……
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = 10010;
int n = scanner.nextInt(), m = scanner.nextInt();
int[][] g = new int[n + 1][n + 1];
int[] distance = new int[n + 1];
boolean[] state = new boolean[n + 1];
// 初始化图和距离数组
Arrays.fill(distance, N);
distance[1] = 0;
for (int[] i : g)
Arrays.fill(i, N);
while (m-- > 0) {
int x = scanner.nextInt(), y = scanner.nextInt(), z = scanner.nextInt();
g[x][y] = Math.min(g[x][y], z); // 题目中有重边,只要留下最小的
}
dijkstra(n, g, distance, state);
if (distance[n] == N)
System.out.println(-1);
else
System.out.println(distance[n]);
scanner.close();
}
private static void dijkstra(int n, int[][] g, int[] distance, boolean[] state) {
// 找起点到别的点的最短路径,共需要n-1次
int m = n - 1;
while (m-- > 0) {
int indexOfMin = -1;
for (int j = 1; j <= n; j++) {
if (!state[j] && (indexOfMin == -1 || distance[j] < distance[indexOfMin])) {
indexOfMin = j;
}
}
for (int j = 1; j <= n; j++) {
distance[j] = Math.min(distance[j], distance[indexOfMin] + g[indexOfMin][j]);
}
state[indexOfMin] = true;
}
}
}