CCF 201412-4

CCF 201412-4

思路是Kruskal算法,简单易懂,不好意思没写注释。

#include<stdio.h>
#include <iostream>
#include <string>
#include <map>
#include <algorithm>

using namespace std;
int path_num,node_num;
int fa[1010];

struct Path{
    int from,des;
    int val;
}p[100010];

bool cmp(Path p1,Path p2){
    return p1.val<p2.val;
}

int father(int x){
    if(fa[x]==x){
        return x;
    }else{
        fa[x]=father(fa[x]);
        return fa[x];
    }
}

int main(){

    for(int i=0;i<1010;i++) fa[i]=i;

    cin >> node_num >> path_num;
    for(int i=0;i<path_num;i++){
        cin >> p[i].from >> p[i].des >> p[i].val;
    }
    sort(p,p+path_num,cmp);
    for(int i=0;i<path_num;i++){
//        cout <<  p[i].from  << ' ' <<  p[i].des  << ' ' <<  p[i].val << endl;
    }
    int ans=0;
    for(int i=0;i<path_num;i++){
//        cout << father(p[i].des) << ' ' << father(p[i].from) << endl;
        if(father(p[i].des)!=father(p[i].from)){
            ans+=p[i].val;
            fa[fa[p[i].des]]=fa[p[i].from];
//            cout << father(p[i].des) << ' ' << father(p[i].from) << endl;
        }
    }
    cout << ans;
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值