JAVA CCF-201503-4 网络延时

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


题目描述

在这里插入图片描述


思路过程

题目求的是树的最长路径
最长距离 = 最大的两个子节点高度和 || 节点的最深深度
构建一个类作为树的节点,height表示树的最深深度,child存储子节点的编号,对于连接了电脑的交换机来说,height初始值应该为1。
进行DFS遍历,不断更新最长距离和节点的最深深度,具体看下面代码。


代码

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	
	static ArrayList<Node> tree;//树
	static int max = 0;//最远距离
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt(), m = in.nextInt();
		tree = new ArrayList<Node>();
		tree.add(new Node());//补充0节点
		for ( int i = 0; i < n; i++ ) tree.add(new Node());
		for ( int i = 2; i <= n; i++ ) {//构建树
			tree.get(in.nextInt()).child.add(i);
		}
		for ( int i = 0; i < m; i++ ) {//连接电脑
			tree.get(in.nextInt()).height = 1;
		}
		DFS(1);
		max = Math.max(max, tree.get(1).height);//特殊情况---只有一个交换机
		System.out.println(max);
	}
	
	//DFS遍历,返回该点的高度
	public static int DFS( int index ) {
		if ( tree.get(index).child.size() != 0 ) {
			for ( int next: tree.get(index).child ) {
				int child_height = DFS(next)+1;//子节点的高度
				max = Math.max(max, child_height + tree.get(index).height);//最大长度 = 最大的两个子节点高度和
				tree.get(index).height = Math.max(child_height, tree.get(index).height);//赋值为子节点的最大高度
			}
		}
		return tree.get(index).height;
	}
	
}
class Node {
	int height;//存储子节点的最大高度
	ArrayList<Integer> child = new ArrayList<Integer>();//子节点
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值