最小生成树 kruskal算法(模板)
kruskal算法计算最小生成树
const int maxn = 105;
const int maxm = 1050;
int n, m;
int par[maxn];
struct Edge {
int from, to, dist;
}edges[maxm];
bool cmp(Edge x, Edge y) { return x.dist < y.dist; }
int find(int x) { return par[x] == x ? x : par[x] = find(par[x]); }
int kruskal() {
int ans = 0;
for (int i = 0; i < n; ++i) par[i] = i;
sort(edges, edges + m, cmp);
for (int i = 0; i < m; ++i) {
Edge e = edges[i];
int x = find(e.from);
int y = find(e.to);
if (x != y) { ans += e.dist; par[x] = y; }
}
return ans;
}
测试程序
#include<bits/stdc++.h>
using namespace std;
const int maxn = 105;
const int maxm = 1050;
int n, m;
int par[maxn];
struct Edge {
int from, to, dist;
}edges[maxm];
bool cmp(Edge x, Edge y) { return x.dist < y.dist; }
int find(int x) { return par[x] == x ? x : par[x] = find(par[x]); }
int kruskal() {
int ans = 0;
for (int i = 0; i < n; ++i) par[i] = i;
sort(edges, edges + m, cmp);
for (int i = 0; i < m; ++i) {
Edge e = edges[i];
int x = find(e.from);
int y = find(e.to);
if (x != y) { ans += e.dist; par[x] = y; }
}
return ans;
}
int main() {
while (scanf("%d%d", &n, &m) == 2) {
for (int i = 0; i < m; ++i) scanf("%d%d%d", &edges[i].from, &edges[i].to, &edges[i].dist);
cout << kruskal() << endl;
}
return 0;
}
/*
5 7
0 1 100
0 2 30
0 4 10
2 1 60
2 3 60
3 1 10
4 3 50
*/