用c++ 编写一个程序,实现求解带权连通图中最小生成树的算法。利用克鲁斯卡尔算法,输出最小生成树的所有边。
时间: 2023-07-22 10:07:24 浏览: 105
以下是使用C++实现克鲁斯卡尔算法求解带权连通图最小生成树的代码:
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 1005;
struct Edge {
int u, v, w;
bool operator<(const Edge& e) const {
return w < e.w;
}
};
int n, m, fa[MAXN];
vector<Edge> edges, ans;
int find(int x) {
if (x != fa[x]) fa[x] = find(fa[x]);
return fa[x];
}
void kruskal() {
sort(edges.begin(), edges.end());
for (int i = 1; i <= n; ++i) fa[i] = i;
for (int i = 0; i < m; ++i) {
int u = edges[i].u, v = edges[i].v, w = edges[i].w;
int fu = find(u), fv = find(v);
if (fu == fv) continue;
fa[fu] = fv;
ans.push_back(edges[i]);
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
edges.push_back({u, v, w});
}
kruskal();
cout << "Minimum Spanning Tree Edges:" << endl;
for (Edge e : ans) {
cout << e.u << " " << e.v << " " << e.w << endl;
}
return 0;
}
```
输入格式为:第一行为节点数n和边数m,接下来m行为每条边的起点、终点、权值。输出最小生成树的所有边。
阅读全文