求解带权无向图最小生成树的代码
时间: 2023-06-09 09:03:01 浏览: 170
以下是基于Kruskal算法的求解带权无向图最小生成树的代码(使用C++语言实现):
```C++
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 10010;
struct Edge{
int u, v, w;
}e[MAXN];
int fa[MAXN];
int n, m;
int find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
int kruskal() {
sort(e + 1, e + 1 + m, [](Edge x, Edge y) {
return x.w < y.w;
});
for(int i = 1; i <= n; i++) fa[i] = i;
int cnt = 0, res = 0;
for(int i = 1; i <= m; i++) {
int u = e[i].u, v = e[i].v, w = e[i].w;
int fa_u = find(u), fa_v = find(v);
if(fa_u == fa_v) continue;
fa[fa_u] = fa_v;
res += w;
cnt++;
if(cnt == n - 1) break;
}
if(cnt != n - 1) return -1;
return res;
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; i++) {
int u, v, w;
cin >> u >> v >> w;
e[i] = {u, v, w};
}
int ans = kruskal();
cout << ans << endl;
return 0;
}
```
希望能够帮助到你!
阅读全文