话不多说上代码
部分代码参考 https://www.cnblogs.com/tp25959/p/10815931.html
这套代码也能把 Kruskal算法求最小生成树 过掉。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
class Edge
{
int a,b,c; //c是边权
Edge(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
public class Main {
static int N = 510, M = (int) (1e5 + 10);
static int n, m;
static int[] p = new int[N]; //并查集数组
static ArrayList<Edge> e = new ArrayList<>(); //用数组的话就是e[M]
static int find(int x) //并查集
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
n = Integer.parseInt(input[0]);
m = Integer.parseInt(input[1]);
for (int i = 1; i <= n; i ++ ) p[i] = i; //初始化并查集
for (int i = 1; i <= m; i ++ )
{
int u, v, w;
input = br.readLine().split(" ");
u = Integer.parseInt(input[0]);
v = Integer.parseInt(input[1]);
w = Integer.parseInt(input[2]);
e.add(new Edge(u, v, w));
}
e.sort((o1, o2)->{
return o1.c - o2.c; //按边权从小到大排序
});
int res = 0;
for (int i = 0; i < m; i ++ ) //m其实就是e.size()
{
int a = e.get(i).a, b = e.get(i).b, c = e.get(i).c;
if (find(a) != find(b))
{
res += c;
p[find(a)] = find(b);
}
}
//最小生成树存在 ⇆ 图连通。所以统计 root 结点个数,大于1就不连通。
int cnt = 0;
for (int i = 1; i <= n; i++)
if (p[i] == i)
{
cnt++;
if (cnt > 1) break;
}
if(cnt == 1) System.out.println(res);
else System.out.println("impossible");
}
}