欢迎访问我的CCF认证解题目录
题目描述
思路过程
题目写得比较复杂,其实就是求最小生成树的最大边,直接套最小生成树的模板修改一下即可
代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
public static int[] father = new int[500005];
//采用克鲁斯卡尔算法,求最小生成树的最大边
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine()), m = Integer.parseInt(br.readLine());
int root = Integer.parseInt(br.readLine()), count = 0, max = 0; //计数和最大边
PriorityQueue<Edge> edges = new PriorityQueue<Edge>(new Comparator<Edge>() {
@Override
public int compare(Edge o1, Edge o2) {
return o1.time - o2.time;//按time升序
}
});
for ( int i = 1; i < n+1; i++ ) father[i] = i;
for ( int i = 0; i < m; i++ ) {
String[] line = br.readLine().split(" ");
edges.offer(new Edge(Integer.parseInt(line[0]), Integer.parseInt(line[1]), Integer.parseInt(line[2])));
}
while ( !edges.isEmpty() ) {
Edge e = edges.poll();
int father1 = findFather(e.v1), father2 = findFather(e.v2);
if ( father1 != father2 ) {
father[father1] = father2;
if ( e.time > max ) max = e.time;
if ( ++count == n-1 ) break;//以连接所有边
}
}
System.out.println(max);
}
//路径压缩
public static int findFather( int index ) {
if ( father[index] == index ) return index;
else {
int temp = findFather(father[index]);
father[index] = temp;
return temp;
}
}
}
class Edge {//存储边
int v1,v2,time;
public Edge(int v1, int v2, int time) {
this.v1 = v1;
this.v2 = v2;
this.time = time;
}
}