zoukankan      html  css  js  c++  java
  • 还是畅通工程(HDU 1233)

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


    Input

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


    Output

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


    Sample Input

    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

    3
    5
    Huge input, scanf is recommended.
    #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
    ",ans);
        }
        return 0;
    }
    
  • 相关阅读:
    C#练习代码
    docker部署gitlab
    vim 缩进设置
    css 初步学习笔记
    tomcat
    201871010107公海瑜《面向对象程序设计(java)》第一周学习总结 公海瑜
    发现JavaScript真强大
    今天看了一點ant的內容,受益匪浅
    一道趣味問題
    一個挺適合初學者的Ant教程
  • 原文地址:https://www.cnblogs.com/lcchy/p/10139592.html
Copyright © 2011-2022 走看看