<span>AcWing 859. Kruskal算法求最小生成树</span>

AcWing 859. Kruskal算法求最小生成树


#include <bits/stdc++.h>
using namespace std;
const int N=2e5+10;
int n,m;
int p[N];
struct Node{
    int a,b,w;

    bool operator< (const Node &W)const{
        return w<W.w;
    }
}nodes[N];
int find(int x){
    if(p[x]!=x) p[x]=find(p[x]);
    return p[x];
}
int main(){
    scanf("%d%d",&n,&m);

    for(int i=0;i<m;i++){
        int a,b,w;
        scanf("%d%d%d",&a,&b,&w);
        nodes[i]={a,b,w};
    }
    sort(nodes,nodes+m);
    int res=0,cnt=0;
    for(int i=1;i<=n;i++) p[i]=i;

    for(int i=0;i<m;i++){
        int a=nodes[i].a,b=nodes[i].b,w=nodes[i].w;
        a=find(a),b=find(b);
        if(a!=b){
            p[a]=b;
            res+=w;
            cnt++;
        }
    }
    if(cnt<n-1) printf("impossible");
    else printf("%d",res);
    return 0;
}

全部评论

相关推荐

07-07 12:47
门头沟学院 Java
码农索隆:竟然还真有卡体检报告的
点赞 评论 收藏
分享
07-10 14:08
已编辑
江西农业大学 Java
拒绝无效加班的小学生...:期望3k吗?java这辈子有了
点赞 评论 收藏
分享
昨天 11:23
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务