JAVA CCF-201503-4 网络延时

爱⌒轻易说出口 提交于 2019-12-09 11:52:49

题目描述

在这里插入图片描述


思路过程

题目求的是树的最长路径
最长距离 = 最大的两个子节点高度和 || 节点的最深深度
构建一个类作为树的节点,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>();//子节点
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!