• 畅通工程——D


                                                        D. 畅通工程

    省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
     

    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
    ?

    分析:用Kruskal算法



    #include <cstdio>
    #include <iostream>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    using namespace std;
    const int MAXN=105;
     int p[MAXN];
     bool sum[MAXN];
     struct node
     {
         int x,y,l;
     }a[5000];
     bool cmp(node a,node b)
     {
         return a.l<b.l;
     }
     int Find(int x)
     {
         return x==p[x]?x:(p[x]=Find(p[x]));
     }
    int  Union(int  R1,int R2)
     {
    
         int r1=Find(R1);
         int r2=Find(R2);
         if(r1!=r2)
         {
             p[r1]=r2;
            return 0;
         }
         else return 1;
     }
    int main()
    {
        int n,m;
        int u,v,y,cnt,i;
    
        while( scanf("%d%d",&n,&m)&&n)
        {
            cnt=0;
          memset(sum,0,sizeof(sum));
           for(i=1;i<=m;i++)
               p[i]=i;
            for(i=1;i<=n;i++)
              scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].l);
                sort(a+1,a+n+1,cmp);
         for(i=1;i<=n;i++)
         {
             if(Union(a[i].x,a[i].y)==0)
                cnt+=a[i].l;
         }
         for(i=1;i<=m;i++)
         {
             sum[Find(i)]=true;
         }
         int k=0;
         for(i=1;i<=m;i++)
         {
             if(sum[i]==true)
                k++;
         }
         if(k!=1)
         cout<<'?'<<endl;
         else
         printf("%d
    ",cnt);
        }
        return 0;
    }
     
  • 相关阅读:
    Windows下Subversion配置管理员指南
    asp.net HttpHand和HttpModule的详细解释,包括Asp.Net对Http请求的处理流程。
    SQL Server 2000不能远程连接的问题
    ASP通用分页类[强]
    不错的站长工具网址(不断收集中....)
    函数的四种调用模式
    HDOJ 3943 Kth Nya Number(数位DP)
    HDOJ 2196 Computer
    HDOJ 3695 Computer Virus on Planet Pandora (AC自动机)
    HDOJ 4277 USACO ORZ (搜索+剪枝)
  • 原文地址:https://www.cnblogs.com/fenhong/p/5318232.html
Copyright © 2020-2023  润新知