参考代码:
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 人评分
C语言程序设计教程(第三版)课后习题8.6 (C语言代码)浏览:530 |
母牛的故事 (C语言代码)浏览:435 |
C语言程序设计教程(第三版)课后习题11.3 (C语言代码)浏览:1020 |
C语言程序设计教程(第三版)课后习题6.9 (C语言代码)浏览:994 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:574 |
C语言程序设计教程(第三版)课后习题8.8 (C语言代码)浏览:1415 |
C语言程序设计教程(第三版)课后习题9.10 (C语言代码)浏览:819 |
循环入门练习6 (C语言代码)浏览:953 |
蛇行矩阵 (C语言代码)浏览:498 |
Quadratic Equation (C语言代码)浏览:988 |