利用最小生成树找到能够遍历全部节点的最短路径
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("data.txt")));
String[] inputs = br.readLine().trim().split(" ");
int n = Integer.parseInt(inputs[0]);
int m = Integer.parseInt(inputs[1]);
int[][] edge = new int[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
edge[i][j] = -1;
}
}
String[] us = br.readLine().trim().split(" ");
String[] vs = br.readLine().trim().split(" ");
String[] ws = br.readLine().trim().split(" ");
for (int i = 0; i < m; i++) {
int u = Integer.parseInt(us[i]);
int v = Integer.parseInt(vs[i]);
int len = Integer.parseInt(ws[i]);
edge[u][v] = len;
edge[v][u] = len;
}
Map<Integer, Integer> mp = new HashMap<>(); // 用来记录已访问的节点
List<Integer> vt = new ArrayList<>(); // 访问顺序
// 从第一个节点开始
mp.put(1, 1);
vt.add(1);
long ans = 0;
int minLen;
int node;
for (int i = 0; i < n - 1; i++) { // 总共有n-1条边
minLen = Integer.MAX_VALUE;
node = -1;
for (int cur : vt) { // 选择离选点最近的点
for (int k = 1; k <= n; k++) { // 在 1 - n 中查找节点
if (mp.containsKey(k)) continue; // 跳过已选择的点
if (edge[cur][k] == -1) continue; // 无边
// 找到最小的边
if (edge[cur][k] < minLen) {
node = k;
minLen = edge[cur][k];
}
}
}
ans += minLen;
mp.put(node, 1); // 标记为已选择
vt.add(node);
}
System.out.println(ans);
}
}
网友评论