ProgramAlgTrain/20240919/CSP常考算法模板/最小生成树/最小生成树_kruskal(稀疏图).cpp

83 lines
1.1 KiB
C++
Raw Normal View History

2024-09-19 02:22:41 +00:00
#include <bits/stdc++.h>
using namespace std;
struct edge {
int x, y, w;
} a[10001];
int f[101];
int ans, cnt;
bool cmp(edge x, edge y) {
return x.w < y.w;
}
//int getDistance(int x1, int y1, int x2, int y2) {
// return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // <20><><EFBFBD><EFBFBD>Ҫ<EFBFBD><D2AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ƽ<EFBFBD><C6BD>
//}
int n, m;
int find(int x) {
if (x == f[x])
return x;
return f[x]=find(f[x]);
}
void merge(int x, int y) {
int fx = find(x);
int fy = find(y);
if (fx != fy) {
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
f[fy] = fx;
}
}
void kruskal()
{
for (int i = 1; i <= n; i++) {
f[i] = i;
}
for (int i = 1; i <= m; i++) {
int u=a[i].x;
int v=a[i].y;
if(find(u)!=find(v))
{
cnt++;
ans+=a[i].w;
merge(u,v);
}
if(cnt==n-1)
{
break;
}
}
}
int main() {
cin>>n>>m;
for (int j = 1; j <= m; j++) {
cin>>a[j].x>>a[j].y>>a[j].w;
}
sort(a + 1, a + m + 1, cmp); //<2F><><EFBFBD><EFBFBD>
kruskal();
cout << ans << endl;
return 0;
}
/*
6 9
2 4 11
3 5 13
4 6 3
5 6 4
2 3 6
4 5 7
1 2 1
3 4 9
1 3 2
*/