洛谷——最小生成树模板

https://www.luogu.org/problemnew/show/P3366

#include <cstdio>
#include <algorithm> 
using namespace std;
const int maxn = 2000005; 
const int maxx = 5005;
int root[maxx];
int find(int x){
    return x==root[x]?x:root[x]=find(root[x]);
}
struct edge{
    int u,v;
    int cost;
    bool operator <(const edge &b)const{
        return cost < b.cost;
    }
}E[maxn];
int main(){
    int N,M;
    scanf("%d%d",&N,&M);
    for(int i = 0; i < M; i++){
        scanf("%d%d%d",&E[i].u,&E[i].v,&E[i].cost);
    }
    sort(E,E+M);
    for(int i = 1;i <= N; i++){
        root[i] = i;
    }
    int total = 0;
    for(int i=0;i<M;i++){
        int faU = find(E[i].u);
        int faV = find(E[i].v);
        if(faU != faV){
            root[faU] = faV;
            total += E[i].cost;
        } 
    }
    printf("%d\n",total);
    return 0;
}
全部评论

相关推荐

07-15 14:14
门头沟学院 Java
7.10投递7.15感谢信
投递地平线等公司10个岗位
点赞 评论 收藏
分享
05-28 16:06
门头沟学院 Java
嵐jlu:我是山川🐔里🐔🧱的,阿里系简历全过; 你这简历一看就还是半成品啊,没有荣誉经历奖项什么的吗?
投递阿里巴巴集团等公司8个岗位
点赞 评论 收藏
分享
积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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