Not to mention the concept of minimum spanning tree, this article mainly implements Kruskal's algorithm, and uses the idea of union search. Compared with the prim algorithm, Kruskal is easier to understand: in the case of not forming a ring, the smallest weight edge is selected until the number of points is reduced by one. For the judgment of the ring, the idea of consolidating and collecting is used. This article gives a template:
#include<bits/stdc++.h>
using namespace std;
const int max_one = 1000;
struct node {
int u, v, w; // u, v代表边,w代表权值
}bian[max_one];
static bool cmp(node a, node b) {
return a.w < b.w;
}
int find(int x) {
if (x == a[x])
return x;
else
return a[x]=find(a[x]); // 使用这种形式,不要return find(a[x]),减少重复递归
}
int a[max_one]; // a数组就是存储并查集每一个节点父节点
int main(void) {
// 假设有n个点,m条边
for (int i=1; i<=n; i++) {
a[i] = i; // 初始化并查集数组为自身
}
输入m条对应边及权值
sort(bian+1, bian+1+m, cmp); // 对权值进行排序,自定义cmp函数
int ans = 0;
int bian_num = 0;
for (int i=1; i<=m && bian_num != n-1; i++) {
int u = bian[i].u;
int v = bian[i].v;
int w = bian[i].w;
int fu = find(u);
int fv = find(v);
if (fu == fv)
continue;
a[fv] = fu;
ans += w;
bian_num++;
}
cout << ans << endl; // ans即为最小权值
return 0;
}
Reference materials:
https://blog.csdn.net/uestct/article/details/47282191
https://blog.csdn.net/qq_40772692/article/details/79667455
Due to the limited level of the author, if there is any mistake, please point it out in the comment section below, thank you!