最小生成树的概念就不说了,本文主要是克鲁斯卡尔算法实现,而且用到了并查集思想。相较于prim算法,克鲁斯卡尔更容易理解:在不形成环的情况下,选取最小的权值边,直到点的个数减一。对于环的判断就使用并查集思想。本文给出一个模板:
#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;
}
参考资料:
https://blog.youkuaiyun.com/uestct/article/details/47282191
https://blog.youkuaiyun.com/qq_40772692/article/details/79667455
因作者水平有限,如有错误之处,请在下方评论区指出,谢谢!