GabrielxD


私信TA

用户名:GabrielxD

访问量:339

签 名:

等  级
排  名 36614
经  验 373
参赛次数 3
文章发表 1
年  龄 19
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

参考代码:

import java.util.*;

public class Main {
    public static Map<Integer, List<Integer>> nodeToChildren;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        nodeToChildren = new HashMap<>();

        for (int i = 2; i <= N; i++) {
            int parent = sc.nextInt();
            if (!nodeToChildren.containsKey(parent)) {
                nodeToChildren.put(parent, new ArrayList<>());
            }
            nodeToChildren.get(parent).add(i);
        }

        System.out.println(getMaxHeight(1));
    }

    public static int getMaxHeight(int node) {
        if (!nodeToChildren.containsKey(node)) {
            return 0;
        }

        int max = 0;
        List<Integer> children = nodeToChildren.get(node);
        for (int child : children) {
            max = Math.max(max, getMaxHeight(child));
        }
        return max + children.size();
    }
}


 

0.0分

2 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区