AcWing 858. Prim算法求最小生成树-java
原题链接
简单
作者:
Astarion
,
2021-02-15 21:47:15
,
所有人可见
,
阅读 266
import java.io.*;
import java.util.Arrays;
class Main {
static final int INF = 0x3fffffff;
//稠密图,邻接矩阵存放
static int n, m;
static int[][] g = new int[550][550];
//dist数组存放结点到生成树集合的距离
static int[] dist = new int[550];
//存放是否已加入生成树中
static boolean[] flag = new boolean[550];
//权重之和
static int sum;
//点数之和
static int cnt;
static {
for (int i = 0; i < 520; i++) {
Arrays.fill(g[i], INF);
g[i][i] = 0;
}
Arrays.fill(dist, INF);
}
static void insert(int a, int b, int c) {
//忽略自环
if (a == b) return;
g[a][b] = g[b][a] = Math.min(g[a][b], c);
}
static boolean prime() {
//从第一个顶点开始找
dist[1] = 0;
for (int i = 1; i <= n; i++) {
int t = 0;
for (int j = 1; j <= n; j++)
if (!flag[j] && dist[j]<dist[t]) t = j;
if (t == 0) break;
flag[t] = true;
sum += dist[t];
cnt++;
if (cnt == n) return true;
//注意,更新距离时使用t点到j点与原j点距离对比
for (int j = 1; j <= n; j++) if (!flag[j]) dist[j] = Math.min(g[t][j], dist[j]);
}
return cnt == n;
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
n = Integer.parseInt(strs[0]);
m = Integer.parseInt(strs[1]);
for (int i = 0; i < m; i++) {
strs = in.readLine().split(" ");
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
int c = Integer.parseInt(strs[2]);
insert(a, b, c);
}
in.close();
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
if (prime()) out.write(sum + "");
else out.write("impossible");
out.flush();
out.close();
osw.close();
}
}