codeup 建设电力系统 最小生成树问题 采用kruskal方法(选取n-1条边所以此方法适合稀疏图)

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn=501,maxsize=124751;
struct Edge
{
    int u;
    int v;
    int price;

};
vector<struct Edge>ve;
int father[maxn];
int findfather(int x)
{
       if(x==father[x])
              return x;
       else
       {
         int F=findfather(father[x]);//
         father[x]=F;
         return F;

       }
}
void Union(int a,int b)
{
     int fa=findfather(a);
     int fb=findfather(b);
     if(fa!=fb)
              father[fa]=fb;

}
int cmp(struct Edge a,struct Edge b)
{
    return a.price<b.price;

}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
       int n,e,sum=0,cnt=0;
       cin>>n>>e;
       ve.clear();
       //初始化
       for(int i=0;i<n;++i)
              father[i]=i;
       for(int i=0;i<e;++i)
       {
              int a,b,k;
              cin>>a>>b>>k;
              struct Edge edge;
              edge.u=a;
              edge.v=b;
              edge.price=k;
              ve.push_back(edge);
       }
       sort(ve.begin(),ve.end(),cmp);
       //n个顶点要想全部连通 并且不出现还那么至少要有n-1条边
       for(int i=0;i<ve.size();++i)
       {

           int fu=findfather(ve[i].u);
           int fv=findfather(ve[i].v);
           if(fu!=fv)//只要两个端点不在一个联通块里面 就可以加入生成树
           {
              sum+=ve[i].price;
              cnt++;//边数累计 只要达到n-1条就break
              father[fu]=fv;
           }
           if(n-1==cnt)
              break;


       }
       cout<<sum<<endl;



    }
    return 0;
}

http://codeup.cn/problem.php?id=1121

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值