Kruskal™
2025-08-07 18:48:27
发布于:上海
0阅读
0回复
0点赞
#include<iostream>
#include<algorithm>
int n,m,x,y,z,u,v,w,b[100001],t[100001];
int get(int);
void merge(int,int);
struct edge{
int u,v,w;
friend bool operator<(edge x,edge y){
return x.w<y.w;
}
}a[200001];
int main(){
long long ans=0;
std::cin.tie(0)->sync_with_stdio(0);
std::cout.tie(0);
std::cin >> n >> m;
for(int i(1);i<=n;++i)b[i]=i;
for(int i(0);i<m;++i)std::cin >> a[i].u >> a[i].v >> a[i].w;
std::sort(a,a+m);
for(int i(0);i<m;++i){
if(get(a[i].u)==get(a[i].v))continue;
merge(a[i].u,a[i].v),--n,ans+=a[i].w;
}
if(n!=1)std::cout << "orz";
else std::cout << ans;
return 0;
}
int get(int idx){
if(idx==b[idx])return idx;
return b[idx]=get(b[idx]);
}
void merge(int x,int y){
int fx=get(x),fy=get(y);
if(fx==fy)return;
if(t[fx]>t[fy])b[fy]=fx;
else{
b[fx]=fy;
if(t[fx]==t[fy])++t[fy];
}
}
这里空空如也
有帮助,赞一个