Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从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
?
这道题其实就是求是否能形成最小生成树,最小生成树算法= 边的权值排序 + 并查集。
import java.util.*;
public class Main {
private static class Edge {
int data;//权值
int from;//节点
int to;//节点
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int N = sc.nextInt();
if (N == 0)
break;
int M = sc.nextInt();
int[] set = new int[M + 1];
for (int i = 1; i <= M; i++) {
set[i] = i;//初始化
}
Edge[] edges = new Edge[N];
for (int i = 0; i < N; i++) {
Edge edge = new Edge();
edge.from = sc.nextInt();
edge.to = sc.nextInt();
edge.data = sc.nextInt();
edges[i] = edge;
}
Arrays.sort(edges, new Comparator<Edge>() {
@Override
public int compare(Edge o1, Edge o2) {
if (o1.data > o2.data)
return 1;
else
return -1;
}
});
int count = 0;
int sum = 0;
for (int i = 0; i < N; i++) {
if (count == M - 1) {
break;
}
int from = edges[i].from;
int to = edges[i].to;
if (set[from] == set[to]) {//如果会形成环(回路)
continue;
}
count++;
sum += edges[i].data;
relation(set, from, to);
}
if (count == M - 1)//如果count == M - 1,说明已形成最小生成树,输出统计的结果。
System.out.println(sum);
else{
System.out.println("?");
}
}
}
/**
* 将两个节点连接
*
* @param set 并查集数组
* @param a 节点
* @param b 节点
*/
public static void relation(int[] set, int a, int b) {
int x = find(set, a);
int y = find(set, b);
if (x < y)
set[y] = x;
else {
set[x] = y;
}
}
/**
* 查找a节点的顶头上司,并做一个路径压缩。
*
* @param set 并查集数组
* @param a 节点
* @return
*/
public static int find(int[] set, int a) {
int res = a;
while (set[res] != res) {
res = set[res];
}
//路径压缩
while (a != res) {
int j = set[a];
set[a] = res;
a = j;
}
return res;
}
}