hdu1863 暢通工程 kruskal




暢通工程

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 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
 

Sample Output
3 ?
 

Source

一道題被寫了第三遍,但是這次卻提交了好幾遍(注意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);
			else
				System.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;
     }
	@Override
	public int compareTo(MAP o) {
		 
		return this.spend - o.spend;//這個平時還真沒咋的用。瞭解了!(注意Comparable與Comparator的區別)
	}
	}	

 
發佈了145 篇原創文章 · 獲贊 27 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章