克鲁斯卡尔算法用C++实现
时间: 2023-12-22 22:27:37 浏览: 85
kruscal算法C++
以下是用C++实现克鲁斯卡尔算法的示例代码:
```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
int n, m, ans;
int fa[MAXN];
struct Edge {
int u, v, w;
} e[MAXN * MAXN];
bool cmp(Edge a, Edge b) {
return a.w < b.w;
}
int find(int x) {
if (fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
void merge(int x, int y) {
int fx = find(x), fy = find(y);
if (fx != fy) fa[fx] = fy;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> e[i].u >> e[i].v >> e[i].w;
}
sort(e + 1, e + m + 1, cmp);
for (int i = 1; i <= n; i++) fa[i] = i;
for (int i = 1; i <= m; i++) {
int u = e[i].u, v = e[i].v, w = e[i].w;
if (find(u) != find(v)) {
merge(u, v);
ans += w;
}
}
cout << ans << endl;
return 0;
}
```
阅读全文