图_最小生成树_克鲁斯卡尔算法-HDU-1233


Date: 2019-9-1
Author: ZLR
Problem: HDU-1233
Degree: ※※
Algorithm: Kruscal


思路:
每个点初始化为一个集合,用struct存边,自定义sort按照权从小到大排序边,
运用并查集来实现顶点集合的查询与合并,包含全部顶点时,
运行n-1次(第一次会有两个顶点),可生成最小生成树

代码:

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<stdlib.h>
#include<string>
#include<algorithm>
#define INF 0x3f3f3f3f
#define maxn 105
using namespace std;
int father[maxn];

int Find(int x){
   if(x==father[x])
   return x;
   else
    return father[x]=Find(father[x]);
}
int judge(int x,int y)
{
    int xx=Find(x);
    int yy=Find(y);
    if(xx!=yy)
    {
        father[xx]=yy;
        return 1;
    }
    else
        return 0;
}
struct bian{
int u,v,w;
};
bool cmp(bian &a,bian &b)
{
    return a.w<b.w;
}
bian arr[5005];
int main()
{
    int n;
    int ans;
    int k;
    while(scanf("%d",&n)&&n){
        for(int i=1;i<=n*(n-1)/2;i++){
            scanf("%d %d %d",&arr[i].u,&arr[i].v,&arr[i].w);
        }
        ans=0;
        k=0;
        sort(arr+1,arr+1+n*(n-1)/2,cmp);
        for(int i=1;i<=n;i++){
            father[i]=i;
        }
        for(int i=1;k<n-1;i++){
            if(judge(arr[i].u,arr[i].v)){
                k++;
              ans+=arr[i].w;
            }
        }
        cout<<ans<<endl;

    }
return 0;}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值