hdu 1863畅通工程

http://acm.hdu.edu.cn/showproblem.php?pid=1863

畅通工程

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9952    Accepted Submission(s): 3929


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 ?
 
Source
View Code
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 int  root[105];
 5 struct Node
 6 {
 7     int u;
 8     int v;
 9     int len;
10 }node[105];
11 int cmp(const void *a,const void *b)
12 {
13     return (*(Node*)a).len>(*(Node*)b).len?1:-1;//结构体按len从小到大排序 
14 }
15 int find(int x)
16 {
17     int r=x;
18     while(r!=root[r])
19     {
20         r=root[r];
21     }
22     
23     int i=x;
24     int j;
25     while(i!=r)
26     {
27         j=root[i];
28         root[i]=r;
29         i=j;
30     }
31     
32     return r;
33 }
34 
35 void merge(int x,int y)
36 {
37     
38     
39     int fx,fy;
40     fx=find(x);
41     fy=find(y);
42     if(fx!=fy) root[fx]=fy;
43 }
44 
45 
46 
47 int main()
48 {
49     int n,m;
50     int i,j,k;
51     
52     while(~scanf("%d%d",&n,&m),n)
53     {
54         for(i=1;i<=m;i++)
55         root[i]=i;
56         int sum=0;
57         for(i=0;i<n;i++)
58         {
59             scanf("%d%d%d",&node[i].u,&node[i].v,&node[i].len);
60             
61         }
62         
63         qsort(node,n,sizeof(node[0]),cmp);
64         
65         for(i=0;i<n;i++)
66         {
67             if(find(node[i].u)!=find(node[i].v))
68             {
69                 merge(node[i].u,node[i].v);
70             sum+=node[i].len;
71             }
72         }
73         int count=0;
74         for(i=1;i<=m;i++)
75         root[i]=find(i);
76         for(i=1;i<=m;i++)
77         {
78             if(root[i]==i)
79             count++;
80         }
81         if(count>1) printf("?\n");
82         else printf("%d\n",sum);
83     }
84     
85     
86 }
原文地址:https://www.cnblogs.com/1114250779boke/p/2633754.html