// 面向多叉树构建邻接表 // 找任意一点d通过dfs找到离它距离最远的点,比如Q,Q肯定是多叉树直径的端点 // 以Q为起点,找到最长路径 import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static int longest = 0; public static int duandian = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int n = sc.nextInt(); sc.nextLine(); List<List<Integer>> adja = new ArrayList<>(); for(int i = 0; i <= n; i++){ adja.add(new ArrayList<>()); } //1.邻接表存储树 for(int i = 2; i <= n ; i++){ int num = sc.nextInt(); adja.get(i).add(num); adja.get(num).add(i); }
点赞 1

相关推荐

牛客网
牛客网在线编程
牛客网题解
牛客企业服务