zoukankan      html  css  js  c++  java
  • ACM 还是畅通工程

    Problem Description
    某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
     
    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
    Hint
    Hint
    Huge input, scanf is recommended.
     
     
    题解:会用并查集就可以AC 没有坑!!!!
     1 /*
     2     Time: 2017/8/8
     3     Author: WTZPT
     4 */
     5 #include<iostream>
     6 #include<cstring>
     7 #include<algorithm>
     8 using namespace std;
     9 int parent[105];
    10 
    11 struct node{    //定义一个结构体,方便数据收集 
    12     int a,b,s;   //a,b是两个村庄的编号 s是两个村庄的距离 
    13 }caseii[5005]; 
    14 
    15 void init()   //初始化parent数组  
    16 {
    17     for(int i = 0; i < 105; i++)
    18         parent[i] = i;    
    19 } 
    20 
    21 bool cmp(node a,node b)   //定义sort排序方式 
    22 {
    23     return a.s < b.s;
    24 }
    25 
    26 int find(int n)     //找根值 
    27 {
    28     if(parent[n] == n)
    29         return n;
    30     else
    31         return find(parent[n]);
    32 }
    33 
    34 int  merge(int a,int b)
    35 {
    36     a = find(a);
    37     b = find(b);
    38     if(a != b)
    39     {
    40         parent[b] = a;
    41         return 1;
    42     } 
    43     return 0;
    44 }
    45 
    46 int main()
    47 {
    48     int n;
    49     while(cin>>n&&n)
    50     {
    51         init();
    52         int t = n*(n-1)/2;
    53         for(int i =0; i < t;i++)
    54             cin>>caseii[i].a>>caseii[i].b>>caseii[i].s;
    55         sort(caseii,caseii+t,cmp);
    56         int sum = 0;
    57         for(int i = 0; i < t;i++)
    58         {    
    59             int temp = merge(caseii[i].a,caseii[i].b);
    60             if(temp)  sum += caseii[i].s;
    61         }    
    62         
    63         cout<<sum<<endl;
    64     }    
    65 
    66      return 0;
    67 }
  • 相关阅读:
    相机振动效果(打击屏幕振动)
    Unity3d Shader开发(一)Properties
    指定字符串长度,并对多余的填充
    Render Texture的使用(截取rendertexture的一帧到Texture2D)
    拖尾渲染器 Trail Renderer
    角色控制器 Character Controller
    Spring Boot 的单元测试
    Git 常用命令整理
    孔浩老师的 Struts2 教程听课笔记(思维导图)
    Java 设计模式之 Command 设计模式
  • 原文地址:https://www.cnblogs.com/jj81/p/7305089.html
Copyright © 2011-2022 走看看