P3366 【模板】最小生成树

原题链接

最小生成数模板(K算法)

code

 

#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
const int M=5005;
int father[M];
struct G{
    int from,to,value;
};
G a[N];
bool cmp(G a,G b){
    return a.value<b.value;
}
void build(int n){
    for (int i=1;i<=n;i++) father[i]=i;
}
int find(int x){
    if (father[x]!=x)
        father[x]=find(father[x]);
    return father[x];
}
void Union(int fx,int fy){
    father[fx]=fy;
}
int main(){
    int n,m,sum=0,sum_side=0;
    cin>>n>>m;
    build(n);
    for (int i=1;i<=m;i++){
        cin>>a[i].from>>a[i].to>>a[i].value;
    }
    sort(a+1,a+m+1,cmp);
    for (int i=1;i<=m;i++){
        int fx=find(a[i].from),fy=find(a[i].to);
        if (fx!=fy) {
            sum_side++;
            sum+=a[i].value;
            Union(fx,fy);
        }
    }
    if (sum_side==n-1) cout<<sum<<endl;
    else cout<<"orz\n";
    return 0;
} 

 

posted @ 2024-03-01 15:19  黑屿白  阅读(18)  评论(0)    收藏  举报