AcWing 859. Kruskal算法求最小生成树:JAVA简单版本
原题链接
简单
作者:
ARM
,
2020-08-13 11:05:32
,
所有人可见
,
阅读 421
java 代码
import java.io.*;
import java.lang.*;
import java.util.*;
class Main{
static int n = 0, m = 0, N = 100010;
static PriorityQueue<int[]> q = new PriorityQueue<>((a, b)->{return a[2] - b[2];});//存储递增边长
static int[] p = new int[N];
static int find(int x){
if(p[x] != x)p[x] = find(p[x]);
return p[x];
}
public static void main(String[] args)throws Exception{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String[] params = buf.readLine().split(" ");
n = Integer.valueOf(params[0]);
m = Integer.valueOf(params[1]);
for(int i = 1; i <= m; ++i){
String[] info = buf.readLine().split(" ");
int a = Integer.valueOf(info[0]);
int b = Integer.valueOf(info[1]);
int w = Integer.valueOf(info[2]);
int[] c = {a, b, w};
q.offer(c);
}
for(int i = 1; i <= n; ++i){
p[i] = i;
}
int res = 0;
int cnt = 1;
while(q.size() != 0){
int[] c = q.poll();
int a = find(c[0]);
int b = find(c[1]);
if(a != b){
res += c[2];
p[a] = b;
cnt++;
}
}
if(cnt == n){
System.out.print(res);
}else{
System.out.print("impossible");
}
}
}