题目1017:还是畅通工程
-
题目描述:
-
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
-
输入:
-
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
-
输出:
-
对每个测试用例,在1行里输出最小的公路总长度。
-
样例输入:
-
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
-
样例输出:
-
3 5
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
Comparator<node> sortByWeight = new Comparator<Main.node>() {
@Override
public int compare(node node1, node node2) {
if(node1.weight>=node2.weight){
return 1;
}else{
return -1;
}
}
};
while(cin.hasNext()){
int hourNum = cin.nextInt();
if(hourNum == 0){
break;
}
int roadNum = hourNum*(hourNum-1)/2;
int tree[] = new int[hourNum+1];
int result = 0;
ArrayList<node> nodes = new ArrayList<node>();
for(int i = 0;i<=hourNum;i++){
tree[i] = -1;
}
for(int i = 0;i<roadNum;i++){
node node = new node();
node.a = cin.nextInt();
node.b = cin.nextInt();
node.weight = cin.nextInt();
nodes.add(node);
}
Collections.sort(nodes,sortByWeight);
for(int i = 0;i<roadNum;i++){
int a = findRoot(nodes.get(i).a,tree);
int b = findRoot(nodes.get(i).b,tree);
if(a!=b){
tree[a] = b;
result += nodes.get(i).weight;
}
}
System.out.println(result);
}
}
private static int findRoot(int x, int[] tree) {
if(tree[x] == -1){
return x;
}else{
int temp = findRoot(tree[x], tree);
tree[x] = temp;
return temp;
}
}
public static class node{
public int a;
public int b;
public int weight;
}
}
1.重写排序接口Comparetor
2.Collections.sort(list,comparetor);对数组进行排序。
3.findRoot方法是记录下所有节点的根节点,如果根节点为-1,那么说明该节点是父节点。