83 lines
1.1 KiB
C++
83 lines
1.1 KiB
C++
#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); // 最后要求距离的平方
|
|
//}
|
|
|
|
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) {
|
|
//如果不在一个集合
|
|
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); //排序
|
|
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
|
|
*/
|
|
|
|
|
|
|