首页 > 其他 > 详细

最小生成树 hdu 1233 模板题

时间:2017-12-31 20:18:36      阅读:209      评论:0      收藏:0      [点我收藏+]
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e4+7;
int n,m,cot,sum;
struct edge
{
    int u,v,w;
    bool operator <(const edge &b)const{
        return w<b.w;
    }
}g[maxn];
int f[maxn];
int Find(int x)
{
    return f[x]==x?x:f[x]=Find(f[x]);
}

void kruskal()
{
    cot=0;
    sort(g,g+m);
    for(int i=0; i<m; i++){
        int t1=Find(g[i].u);
        int t2=Find(g[i].v);
        if(t1!=t2){
            f[t2]=t1;
            cot++;
            sum=sum+g[i].w;
        }
        if(cot==n-1) break;
    }
    return ;
}
int main()
{
    while(~scanf("%d",&n)&&n){
        m=n*(n-1)/2;
        sum=0;
        for(int i=0;i<=n;i++)f[i]=i;
        for(int i=0;i<m;i++){
             scanf("%d%d%d",&g[i].u,&g[i].v,&g[i].w);
        }
        kruskal();
        printf("%d\n",sum);
    }
    return 0;
}
/*
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
*/

 

最小生成树 hdu 1233 模板题

原文:https://www.cnblogs.com/lalalatianlalu/p/8158469.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!