暢通工程
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 14333 Accepted Submission(s): 5931
行對應村莊間道路的成本,每行給出一對正整數,分別是兩個村莊的編號,以及此兩村莊間道路的成本(也是正整數)。爲簡單起見,村莊從1到M編號。當N爲0時,全部輸入結束,相應的結果不要輸出。
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的區別)
}
}