前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >还是畅通工程(HDU 1233)

还是畅通工程(HDU 1233)

作者头像
Lokinli
发布2023-03-09 16:26:30
1820
发布2023-03-09 16:26:30
举报
文章被收录于专栏:以终为始以终为始

某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。 

Input

测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。  当N为0时,输入结束,该用例不被处理。 

Output

对每个测试用例,在1行里输出最小的公路总长度。 

Sample Input

代码语言:javascript
复制
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

Sample Output

代码语言:javascript
复制
3
5
Huge input, scanf is recommended.
代码语言:javascript
复制
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node
{
    int b,e;
    int w;
} s[10005];
bool cmp(struct node x, struct node y)
{
    return x.w < y.w;
}
int pre[1000];
int Find(int x)
{
    while(x!=pre[x])
    {
        x = pre[x];
    }
    return x;
}
int Merge(int x, int y)
{
    if(Find(x) != Find(y))
    {
        pre[Find(x)] = Find(y);
        return 1;
    }
    return 0;
}
int kruskal(int n, int x)
{
    int ans = 0, num = 0;
    for(int i =0; i <= n; i ++)
    {
        pre[i] = i;
    }
    for(int i =0; i < x; i ++)
    {
        if(Merge(s[i].b, s[i].e) == 1)
        {
            ans += s[i].w;
            num ++;
        }
        if(num == n - 1)break;
    }
    return ans;
}
int main()
{
    int n,x;
    while(~scanf("%d",&n)&&n)
    {
        x = (n*(n -1)) / 2;
        for(int i = 0; i < (n*(n - 1)) / 2; i ++)
        {
            scanf("%d %d %d",&s[i].b, &s[i].e, &s[i].w);
        }
        sort(s,s + x, cmp);
        int ans = kruskal(n,x);
        printf("%d\n",ans);
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-08-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Input
  • Output
  • Sample Input
  • Sample Output
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档