【NYOJ 38 K r u s k a l】

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=38
/*
问题描述:给定一个图求最小生成树
思路: K r u s k a l算法每次选择n- 1条边,
所使用的贪婪准则是:
从剩下的边中选择一条不会产生环路的具有
最小耗费的边加入已选择的边的集合中。
注意到所选取的边若产生环路则不可能形成一棵生成树。
K r u s k a l算法分e 步,其中e 是网络中边的数目。
按耗费递增的顺序来考虑这e 条边,每次考虑一条边。
当考虑某条边时,若将其加入到已选边的集合中会出现环路,
则将其抛弃,否则,将它选入。
利用并查集的求法判断是否会构成回路:若他们根节点不同则不会有环
*/

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct Edge{
    int a,b;
    int cost;
}edge[505*505/2];
int father[505];
int d[505];
int v,e;
int cmp(Edge x,Edge y){
    return x.cost<y.cost;
}
int ifind(int x){
            if(x==father[x])
                 return x;
            father[x]=ifind(father[x]);
            return father[x];
}
int Union(int x,int y){
    int f1=ifind(x);
    int f2=ifind(y);
    if(f1==f2)
        return false;
    if(f1>f2)
        f2[father]=f1;
    else
        f1[father]=f2;
}
int kurukal(){
    int sum=0;
    for(int i=1;i<=v;i++)
        father[i]=i;
    sort(edge+1,edge+e+1,cmp);
    for(int i=1;i<=e;i++){
         if(Union(edge[i].a,edge[i].b)){
              sum+=edge[i].cost;
         }
    }
    return sum;
}
int main(){
    int test;
    scanf("%d",&test);
    while(test--){
        scanf("%d%d",&v,&e);
        for(int i=1;i<=e;i++){
             scanf("%d%d%d",&edge[i].a,&edge[i].b,&edge[i].cost);
        }
        for(int i=0;i<v;i++){
            scanf("%d",&d[i]);
        }
        sort(d,d+v);
        printf("%d\n",kurukal()+d[0]);

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

paidream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值