题目描述
编程实现Kruskal算法,求图的最小生成树(MST)的权重。
输入
每组数据分为两个部分,第一部分为图的点数n,和边数m,
第二部分为m行,每一行输入三个数字,前两个为两个顶点的编号,第三个为边权重。
输出
最小生成树的权重。
样例输入
3 3
0 1 10
0 2 15
1 2 50
样例输出
25
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
static int pa[];
static int rank[];
static int num;
static class tree implements Comparable<tree> {
int x;
int y;
int w;
@Override
public int compareTo(tree o) {
// TODO Auto-generated method stub
return Integer.compare(w, o.w);
}
tree(int x,int y,int w){
this.x=x;
this.y=y;
this.w=w;
}
}
static int find_set(int x) {//路径压缩查找
if(x!=pa[x]) {
pa[x]=find_set(pa[x]);
}
return pa[x];
}
static boolean union_set(int x,int y,int w) {
x=find_set(x);
y=find_set(y);
if(x==y) {
return false;
}
if(rank[x]>rank[y]) {
pa[y]=x;
} else {
if(rank[x]==rank[y]) rank[y]++;
pa[x]=y;
}
num+=w;
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc =new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
pa=new int[105];
rank=new int[105];
for(int i=1;i<=n;i++) {
pa[i]=i;
rank[i]=0;
}
num=0;
List<tree>trees=new ArrayList<tree>();
for(int i=0;i<m;i++) {
trees.add(new tree(sc.nextInt(), sc.nextInt(), sc.nextInt()));
}
Collections.sort(trees);
for(tree t:trees) {
int x=t.x;
int y=t.y;
int w=t.w;
union_set(x, y, w);
}
System.out.println(num);
}
}