hdu1863 畅通工程 kruskal

来源:互联网 发布:windows subst 编辑:程序博客网 时间:2024/06/06 21:38



畅通工程

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


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

Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
 

Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
 

Sample Input
3 31 2 11 3 22 3 41 32 3 20 100
 

Sample Output
3?
 

Source
浙大计算机研究生复试上机考试-2007年

一道题被写了第三遍,但是这次却提交了好几遍(注意n,m),细节决定成败啊奋斗
思路是很简单,先对边排序(带上边结点),然后每次取最小边集合查找合并边集最小的结点元素集合

import java.io.*;import java.util.*;public class hdu1863畅通工程_Kruskal算法 {private static int find(int r) {while(r!=fa[r])r = fa[r];return r;}   static int fa[];   static int n,m,a,b,c;   static MAP[] map;public static void main(String[] args) {Scanner sc = new Scanner(new InputStreamReader(System.in));while(true){ n = sc.nextInt();//道路条数 m = sc.nextInt();//村庄数目if(n==0)break;fa = new int[m+1];map = new MAP[n+1];for(int i=1;i<=m;i++)fa[i]=i;  for(int i=1;i<=n;i++){a = sc.nextInt();b = sc.nextInt();c = sc.nextInt();map[i] = new MAP(a,b,c);}Arrays.sort(map,1, n+1);//排序int Count=0;long sum = 0; for(int i=1; i<=n; i++){                        int x = find(map[i].pre);//查找或合并边集                        int y = find(map[i].to);                      if(x!=y){//不在一个集合,而且为最小即可加入                          fa[y] = x;                          Count++;                         sum += map[i].spend;                       } }if(Count==m-1)System.out.println(sum);elseSystem.out.println("?");}}}class MAP implements Comparable<MAP>{     int pre,to,spend;     public MAP(int pre,int to,int spend){     this.pre = pre;     this.to = to;     this.spend = spend;     }@Overridepublic int compareTo(MAP o) { return this.spend - o.spend;//这个平时还真没咋的用。了解了!(注意Comparable与Comparator的区别)}}

 
0 0
原创粉丝点击