思路:最小生成树
PS.Java会出现运行超时
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
public class Java_201812_4 {
static int[] fathers;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt(), edge_num = scanner.nextInt(), root = scanner.nextInt();
// 存储边权值对应的边顶点
Map<Integer, Queue<Integer>> map = new HashMap<>();
// 存储边的权值
int[] edge = new int[edge_num];
// 并查集生成
fathers = new int[num + 1];
for (int i = 1; i <= num; i++)
fathers[i] = i;
// 获取边
for (int i = 0; i < edge_num; i++) {
int a = scanner.nextInt();
int b = scanner.nextInt();
edge[i] = scanner.nextInt();
Queue<Integer> list = map.getOrDefault(edge[i], new LinkedList<>());
list.add(a);
list.add(b);
map.put(edge[i], list);
}
Arrays.sort(edge);
scanner.close();
// 生成路径
int route = 0, index = 0, max = 0;
while (route != num - 1) {
int weight = edge[index];
Queue<Integer> queue = map.get(weight);
int a = queue.poll();
int b = queue.poll();
int a_father = getFather(a);
int b_father = getFather(b);
if (a_father != b_father) {
fathers[a_father] = b_father;
route++;
max = weight;
}
index++;
}
System.out.println(max);
}
private static int getFather(int child) {
int father;
while ((father = fathers[child]) != child) {
child = father;
}
return father;
}
}