1.Kruskal算法
此算法可以称为“加边法”,初始最小生成树边数为0,每迭代一次就选择一条满足条件的最小代价边,加入到最小生成树的边集合里。
1. 把图中的所有边按代价从小到大排序;
2. 把图中的n个顶点看成独立的n棵树组成的森林;
3. 按权值从小到大选择边,所选的边连接的两个顶点ui,vi,应属于两颗不同的树,则成为最小生成树的一条边,并将这两颗树合并作为一颗树。
4. 重复(3),直到所有顶点都在一颗树内或者有n-1条边为止。
在这里归纳一下,该算法可以分为两步
1、为边的权值做一个排序。
2、并查集去除环(因为排序之后,如果直接把节点做连接,可能会出现环的情况,这不符合最小生成树,所以用并查集判断是否会出现环,如果会,则不连接。也可理解为确保连接的两个节点不在一颗树上,就像上图所说。)
这里有一篇讲的很好的一道并查集的题:朋友圈的个数你会算吗?
下面为java代码的实现(我用1、2、3、4、5、6 代替 A、B 、C 、D 、E 、F):
import java.io.BufferedInputStream;
import java.util.*;
public class Main {
private static class Edge {
int data;//边的权值
int from;//节点
int to;//节点
}
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int v = sc.nextInt();//节点数
int e = sc.nextInt();//边数
int[][] a = new int[v + 1][v + 1];
Edge[] edges = new Edge[e];
//初始化邻接矩阵(用来展示结果)
for (int i = 1; i <= v; i++) {
for (int j = 1; j <= v; j++) {
a[i][j] = Integer.MAX_VALUE;
}
}
//初始化边的权值,和连接的节点
for (int i = 0; i < e; i++) {
int from = sc.nextInt();//赋值节点
int to = sc.nextInt();//赋值节点
int e_data = sc.nextInt();//赋值边的权值
Edge edge = new Edge();
edge.data = e_data;
edge.from = from;
edge.to = to;
edges[i] = edge;
}
//边的排序。
Arrays.sort(edges, new Comparator<Edge>() {
@Override
public int compare(Edge o1, Edge o2) {
if (o1.data > o2.data)
return 1;
else {
return -1;
}
}
});
//初始化并查集数组
int[] set = new int[e + 1];
for (int i = 1; i <= e; i++) {
//默认该节点的上司是自身
set[i] = i;
}
int count = 0;
for (int i = 0; i < edges.length; i++) {
if (count == v - 1)
break;
int from = edges[i].from;
int to = edges[i].to;
int data = edges[i].data;
if (set[from] == set[to]) {//如果查找集合,两个节点的顶头上司相同,则意味着会构成环。
continue;
}
count++;
relation(set, from, to);//连接两个节点。
a[from][to] = data;
}
//展示结果。
for (int i = 1; i <= v; i++) {
for (int j = 1; j <= v; j++) {
if (a[i][j] != Integer.MAX_VALUE)
System.out.print(a[i][j] + " ");
else
System.out.print("∞" + " ");
}
System.out.println();
}
}
/**
* 将两个节点连接
*
* @param set 并查集数组
* @param a 节点
* @param b 节点
*/
public static void relation(int[] set, int a, int b) {
int x = find(set, a);
int y = find(set, b);
if (x < y)
set[y] = x;
else {
set[x] = y;
}
}
/**
* 查找a节点的顶头上司,并做一个路径压缩。
*
* @param set 并查集数组
* @param a 节点
* @return
*/
public static int find(int[] set, int a) {
int res = a;
while (set[res] != res) {
res = set[res];
}
while (a != res) {
int j = set[a];
set[a] = res;
a = j;
}
return res;
}
}
控制台数据:
6 10
1 2 6
1 3 1
1 4 5
2 3 5
3 4 5
2 5 3
3 5 6
4 6 2
3 6 4
5 6 6
输出结果:
∞ ∞ 1 ∞ ∞ ∞
∞ ∞ 5 ∞ 3 ∞
∞ ∞ ∞ ∞ ∞ 4
∞ ∞ ∞ ∞ ∞ 2
∞ ∞ ∞ ∞ ∞ ∞
∞ ∞ ∞ ∞ ∞ ∞
控制台: