• HDU1863---畅通工程


    Problem Description
    省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
     
    Input
    测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
    行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
     
    Output
    对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
     
    Sample Input
    3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
     
    Sample Output
    3 ?
     
    与之前做过的畅通工程很相似,多了一个值,对值进行排序,以并差集的方式操作。判断道路数是否达到村镇数减一;
    附代码
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<map>
    #include<queue>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    const int maxn=102;
    int n,m;
    int pre[maxn];
    struct rode
    {
        int x;
        int y;
        int z;
    } p[1000];
    int compare(rode node1,rode node2) //排序 ,通过值
    {
        if(node1.z < node2.z)
            return 1;
        return 0;
    }
    void hb()//初始化
    {
        for(int i=1; i<=n; i++)
            pre[i]=i;
    }
    int Find(int x)//路径压缩
    {
        while(x!=pre[x])
            x=pre[x];
        return x;
    }
    void uoin(int x,int y)//合并
    {
        int fx=Find(x);
        int fy=Find(y);
        if(fx!=fy)
            pre[fx]=fy;
    }
    int main()
    {
        while(scanf("%d%d",&n,&m)&&n)
        { 
            int i;
            for(i=0; i<n; i++)
                scanf("%d%d%d",&p[i].x,&p[i].y,&p[i].z);
            sort(p,p+n,compare);
            hb();
            int minz=0,count=0;
            for (i = 0; i < n; i++)
            {
                if (Find(p[i].x) != Find(p[i].y))
                {
                    uoin(p[i].x,p[i].y);
                    minz+= p[i].z;
                    count++;
                    if(count == m-1)
                        break;
                }
            }
            if(count < m-1)
                printf("?
    ");
            else
                printf("%d
    ", minz);
        }
    }
    View Code

    加油加油

  • 相关阅读:
    浅谈Dotnet的数据定位和匹配
    聊聊Dotnet的垃圾回收
    Dotnet中Span, Memory和ReadOnlySequence之浅见
    Dotnet的局部函数和委托的对比
    一文说通Dotnet的委托
    开发进阶:Dotnet Core多路径异步终止
    冷饭新炒:理解布隆过滤器算法的实现原理
    冷饭新炒:理解JWT的实现原理和基本使用
    冷饭新炒:理解JDK中UUID的底层实现
    起飞,会了这4个 Intellij IDEA 调试魔法,阅读源码都简单了
  • 原文地址:https://www.cnblogs.com/She-Chuan/p/9744324.html
Copyright © 2020-2023  润新知