并查集即可

数据的逻辑顺序理清楚就可以了

不然多少有点头大

import java.util.Scanner;
public class Main{
	static int pre[];
	static int comd[];
	static int find(int x) {
		comd[x]++;
		if(pre[x]==x) return x;
		else {
			return find(pre[x]);
		}
	}
	static void link(int x,int y) {
		int xx = find(x);
		int yy = find(y);
		pre[xx] = yy;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		pre = new int[n];
		comd = new int[n];
		for (int i = 0; i < pre.length; i++) {
			pre[i] = i;
		}
		for (int i = 0; i < pre.length; i++) {
			int a = sc.nextInt();
			if(a!=0)
				link(i,a-1);
			else
				comd[a]++;
		}
		for (int i = 0; i < comd.length; i++) {
			System.out.print(comd[i]+" ");
		}
	}
}

 

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐