CCF 201812-4 数据中心 Java

思路:最小生成树
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;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值