题目描述:
输入
第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000)
第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)
输出
输出最小生成树的所有边的权值之和。
输入示例:
9 14
1 2 4
2 3 8
3 4 7
4 5 9
5 6 10
6 7 2
7 8 1
8 9 7
2 8 11
3 9 2
7 9 6
3 6 4
4 6 14
1 8 8
输出示例
37
import java.util.Scanner;
/**
* 第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。
* (2 <= N <= 1000, 1 <= M <= 50000)
* 第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。
* (1 <= S, E <= N,1 <= W <= 10000)
* 输出最小生成树的所有边的权值之和
*/
public class Main{
public static long prim(int[][] a, int N) {
long res = 0;
boolean[] vis = new boolean[N + 5];
int[] min = new int[N + 5];
init(min);
min[1] = 0;
for (int i = 1; i <= N; i++) {
int k = -1;
for (int j = 1; j <= N; j++) {
if (!vis[j] && (k == -1 || min[j] < min[k])) {
k = j;
}
}
vis[k] = true;
res += min[k];
for (int l = 1; l <= N; l++) {
if (!vis[l] && a[k][l] < min[l])
min[l] = a[k][l];
}
}
return res;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int M = scanner.nextInt();
int[][] a = new int[N + 5][N + 5];
init(a);
for (int i = 0; i < M; i++) {
int s = scanner.nextInt();
int e = scanner.nextInt();
int w = scanner.nextInt();
a[s][e] = a[e][s] = w;
}
System.out.println(prim(a, N));
}
public static void init(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
a[i] = Integer.MAX_VALUE;
}
}
public static void init(int[][] a) {
int n = a.length;
int m = a[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = Integer.MAX_VALUE;
}
}
}
}