JAVA CCF-201703-4 地铁修建

欢迎访问我的CCF认证解题目录


题目描述

在这里插入图片描述


思路过程

最开始我以为是求最小生成树的最大边。。。结果错了,重新看了一下题,发现A市决定在1号到n号枢纽间修建一条地铁这句话,只要1和n联通了就好,最小生成树最大边的变形题,所以只要在最小生成树的模板上稍加修改即可,当1和n联通时,就结束循环,输出


代码

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[100005];
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] line = br.readLine().split(" ");
		int n = Integer.parseInt(line[0]), m = Integer.parseInt(line[1]);
		long max = Long.MIN_VALUE;
		PriorityQueue<Edge> edges = new PriorityQueue<Edge>(new Comparator<Edge>() {
			@Override
			public int compare(Edge o1, Edge o2) {
				return o1.cost - o2.cost;	//按时间升序
			}
		});
		
		//初始化
		for ( int i = 1; i < n+1; i++ ) father[i] = i;
		for ( int i = 0; i < m; i++ ) {
			line = br.readLine().split(" ");
			edges.offer(new Edge(Integer.parseInt(line[0]), Integer.parseInt(line[1]), Integer.parseInt(line[2])));
		}
		
		while ( findFather(1) != findFather(n) ) {//判断1和n是否已经联通
			Edge temp = edges.poll();
			int father1 = findFather(temp.v1), father2 = findFather(temp.v2);
			if ( father1 != father2 ) {//如果父母不同,说明没有边连接
				father[father1] = father2;
				if ( temp.cost > max ) max = temp.cost;
			}
		}
		System.out.println(max);
	}
	
	public static int findFather( int index ) {	//路径压缩
		if ( father[index] == index ) return index;
		int temp = findFather(father[index]);
		father[index] = temp;
		return temp;
	}
	
}
class Edge {
	int v1,v2,cost;
	public Edge(int v1, int v2, int cost) {
		this.v1 = v1;
		this.v2 = v2;
		this.cost = cost;
	}
}
发布了60 篇原创文章 · 获赞 0 · 访问量 2133

猜你喜欢

转载自blog.csdn.net/weixin_43732798/article/details/103482123