有一个研究团队,团队分成许多研究小组,每个小组可能再分成小组,求自己及自己带领的小组有多少人
/*研究小组找自己的所处小组有多少组员,类似树状结构 (树形结构如下图)
* 用例参考 Input 6 (表示6个人)
* 0 1 2 1 2 2 (0表示自己是老大,1表示自己的BOSS是1号)
* Output 6 4 1 1 1 1
* */
import java.util.*;
public class hd02 {
static void manageNum(int a[],int n)
{
int b[]=new int [n+1];
for(int i=1;i<n+1;i++)
b[i]=1;
for(int i=1;i<n+1;i++)
{
if(a[i]==0)
continue;
else /* b[i]是专门来存储员工的人数 */
{
int k=i;
while(a[k]!=0)
{
int j=a[k]; /*a[k]是用来找到第k个人的头*/
b[j]++; /*在b[i]中++是来表示人头数+1*/
k=j; /*看第j个位置上面还有没有头*/
}
}
}
for(int i=1;i<n+1;i++)
System.out.print(b[i]);
}
public static void main(String[] args) {
System.out.print("输入团队的总人数:");
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int a[]=new int [n+1];
for(int i=1;i<n+1;i++)
a[i]=input.nextInt();
manageNum(a,n);
System.exit(0);
}
}