package graph.kruskal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Kruskal {
static final int N = 100;
static int fa[] = new int[N];
static int n;
static int m;
static Edge e[] = new Edge[N * N];
static List<Edge> edgeList = new ArrayList();
static {
for (int i = 0; i < e.length; i++) {
e[i] = new Edge();
}
}
// 初始化集合号为自身
static void Init(int n) {
for (int i = 1; i <= n; i++)
fa[i] = i;
}
// 合并
static int Merge(int a, int b) {
int p = fa[a];
int q = fa[b];
if (p == q) return 0;
for (int i = 1; i <= n; i++) { // 检查所有结点,把集合号是 q 的改为 p
if (fa[i] == q)
fa[i] = p; // a 的集合号赋值给 b 集合号
}
return 1;
}
// 求最小生成树
static int Kruskal(int n) {
int ans = 0;
Collections.sort(edgeList);
for (int i = 0; i < m; i++)
if (Merge(edgeList.get(i).u, edgeList.get(i).v) == 1) {
ans += edgeList.get(i).w;
n--;
if (n == 1)//n-1次合并算法结束
return ans;
}
return 0;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
Init(n);
for (int i = 1; i <= m; i++) {
e[i].u = scanner.nextInt();
e[i].v = scanner.nextInt();
e[i].w = scanner.nextInt();
edgeList.add(e[i]);
}
System.out.println("最小的花费是:" + Kruskal(n));
}
}
class Edge implements Comparable {
int u;
int w;
int v;
@Override
public int compareTo(Object o) {
if (this.w > ((Edge) o).w) {
return 1;
} else if (this.w == ((Edge) o).w) {
return 0;
} else {
return -1;
}
}
}
绿色为输入,白色为输出。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/125707976
内容来源于网络,如有侵权,请联系作者删除!