欢迎访问我的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>();//子节点
}