这个畅通工程就不是最小生成树了,而是建好了路,怎么走的问题,最短路径算法。
而且题目中说到会指明起点和终点,那么就是多源汇最短路,要用到Floyd算法。
要注意的是可能存在自环和重边,初始化 i=j 的点初始为0,输入时做最小值判断。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int N = 1010, n, m, start, end;
static int dist[][] = new int[N][N];
static final int INF = 0x3f3f3f3f;
public static void init() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) dist[i][j] = 0;
else dist[i][j] = INF;
}
}
}
public static void main(String[] args) throws IOException {
while (true) {
String input = br.readLine();
if (input == null) break;
init();
String s[] = input.split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
for (int i = 0; i < m; i++) {
s = br.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
int w = Integer.parseInt(s[2]);
dist[a][b] = dist[b][a] = Math.min(dist[a][b], w);
}
Floyd();
s = br.readLine().split(" ");
start = Integer.parseInt(s[0]);
end = Integer.parseInt(s[1]);
if (dist[start][end] >= INF) System.out.println(-1);
else System.out.println(dist[start][end]);
}
}
public static void Floyd() {
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}
}