AcWing 3210. 最优灌溉
原题链接
简单
作者:
把这题Ac了
,
2024-11-14 11:46:02
,
所有人可见
,
阅读 1
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010,M = 1e5 + 10;
typedef long long LL ;
int p[N];
struct node{
int a,b,w;
}edge[M];
bool cmp(node &n1,node &n2){
return n1.w < n2.w;
}
int find(int x){
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main(){
int n,m;
cin >> n >> m;
for(int i = 1;i <= n;i++) p[i] = i;
for(int i = 0;i < m;i++){
int a,b,c;
cin >> a >> b >> c;
edge[i] = {a,b,c};
}
LL res = 0;
sort(edge,edge + m,cmp);
for(int i = 0;i < m;i++){
auto t = edge[i];
int a = t.a,b = t.b,c = t.w;
int pa = find(a),pb = find(b);
if(pa != pb){
p[pb] = pa;
res += (LL)c;
}
}
cout << res << endl;
return 0;
}