Kruskal算法又被称为“加边法”,这种算法会将加权连通图的最小生成树看成具有V-1条边的无环子图,且边的权重和最小。算法开始时,会按照权重的非递减顺序对图中的边排序,之后迭代的以贪婪的方式添加边。
下面以下图为例来讲解Kruskal算法的过程:
Input:
6 10
1 2 3
1 5 6
1 6 5
2 6 5
2 3 1
3 6 4
3 4 6
4 6 5
4 5 8
5 6 2
Output:
15
完整代码如下:
import java.util.Scanner;class edge {int u, v, w;edge(int u, int v, int w) {this.u = u;this.v = v;this.w = w;}
}
public class Main {static edge[] e = new edge[11];static int n, m;static int[] f = new int[7];static int sum = 0;static int count = 0;static Scanner input = new Scanner(System.in);public static void main(String[] args) {n = input.nextInt();m = input.nextInt();for (int i = 1; i <= m; i++) {int a = input.nextInt();int b = input.nextInt();int c = input.nextInt();e[i] = new edge(a, b, c);}/*** 按权值排序* */quicksort(e, 1, m);for (int i = 1; i <= n; i++) {f[i] = i;}kruskal();System.out.println(sum);}private static void kruskal() {/*** 从小到大枚举每一条边* */for (int i = 1; i <= m; i++) {/*** 检查一条边的两个顶点是否已经连通,即判断是否在同一个集合中* */if (merge(e[i].u, e[i].v)) {count++;sum = sum + e[i].w;}/*** 选到n-1边之后,退出循环* */if (count == n - 1) {break;}}}public static int partition(edge[] a, int p, int q) {int x = a[p].w;int i = p;for (int j = p+1; j <= q; j++) {if (a[j].w <= x) {i += 1;edge temp = a[i];a[i] = a[j];a[j] = temp;}}edge temp = a[p];a[p] = a[i];a[i] = temp;return i;}public static void quicksort(edge[] a,int p, int q) {if (p < q) {int r = partition(a ,p ,q);quicksort(a, p, r - 1);quicksort(a, r + 1, q);}}private static int getf(int v) {if (f[v] == v) {return v;} else {/*** 压缩路径,每次函数返回时,将该位置的编号转成祖宗编号* */f[v] = getf(f[v]);return f[v];}}private static boolean merge(int v, int u) {int t1 = getf(v);int t2 = getf(u);/*** 判断祖先是否相同* */if (t1 != t2) {/*** 靠左原则* */f[t2] = t1;return true;}return false;}
}
Kruskal算法的时间复杂度主要取决于对图中的边进行权值排序,如果排序算法效率比较高,那么Kruskal算法的时间复杂度为O(nlogn)