67 路径数组变为统计数组
Table of Contents

ac

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;


public class Main {
    public static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) throws Exception{
        int n = sc.nextInt();
        int root = 0;
        // 构造邻接矩阵
        Map<Integer,LinkedList<Integer>> mp = new HashMap<>(n);
        for(int i=0;i<n;i++){
            int num = sc.nextInt();
            if(i == num){
                root = i;
            }else {
                if (mp.containsKey(num)) {
                    mp.get(num).addLast(i);
                }
                else {
                    LinkedList<Integer> linkedList = new LinkedList<>();
                    linkedList.addLast(i);
                    mp.put(num, linkedList);
                }
            }
        }
        // 利用队列遍历
        int[] ans = new int[n];
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(root);
        int level = 0;
        while (!queue.isEmpty()){
            LinkedList<Integer> tmp = new LinkedList<>();
            int curCnt = 0;
            while (!queue.isEmpty()){
                int val = queue.poll();
                if(mp.containsKey(val) && !mp.get(val).isEmpty()) {
                    tmp.addAll(mp.get(val));
                }
                curCnt ++;
            }
            ans[level++] = curCnt;
            if(tmp.isEmpty()){
                break;
            }
            queue.addAll(tmp);
        }
        for(int i=0;i<n-1;i++){
            System.out.print(ans[i] + " ");
        }
        System.out.println(ans[n-1]);
    }
}
/*
10
9 1 4 9 0 4 8 9 0 1

     1
     |
     9
   / | \
  0  3  7
 /\
4  8
/\  \
2 5  6
 */