参考代码:
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二级辅导-阶乘数列 (C语言代码)浏览:736 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:512 |
IP判断 (C语言描述,蓝桥杯)浏览:1118 |
Tom数 (C语言代码)浏览:758 |
杨辉三角 (C语言代码)浏览:505 |
C语言程序设计教程(第三版)课后习题9.4 (C语言代码)浏览:724 |
C二级辅导-统计字符 (C语言代码)浏览:514 |
IP判断 (C语言代码)浏览:592 |
计算质因子 (C语言代码)浏览:778 |
C语言程序设计教程(第三版)课后习题10.2 (C语言代码)浏览:560 |