AcWing 859. Kruskal算法求最小生成树-java
原题链接
简单
作者:
Susu
,
2020-01-30 23:48:05
,
所有人可见
,
阅读 718
import java.util.*;
class Edge{
int a; int b; int w;
public Edge(int a,int b,int w){
this.a=a; this.b=b; this.w=w;
}
}
public class Main {
static int N = 100010;
static int n,m;
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){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
Edge[] edge = new Edge[m];
for(int i=0;i<m;i++){
int a = sc.nextInt(); int b = sc.nextInt(); int w = sc.nextInt();
Edge e = new Edge(a,b,w);
edge[i]=e;
}
Arrays.sort(edge, new Comparator<Edge>() {
@Override
public int compare(Edge o1, Edge o2) {
if(o1.w<o2.w) return -1;
else if(o1.w>o2.w) return 1;
else return 0;
}
});
for(int i=1;i<n;i++) p[i]=i;
int res=0,cnt=0;
for(int i=0;i<m;i++){
int a = edge[i].a; int b = edge[i].b; int w = edge[i].w;
a = find(a);b=find(b);
if(a!=b){
p[a]=b; res+=w; cnt++;
}
}
if(cnt<n-1) System.out.println("impossible");
else System.out.println(res);
}
}