DFS深度遍历即可。比较简单。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <stack>
#include <cstring>
#include <cmath>
using namespace std;
vector<int> Node[100000];
int hashset[10000]= {0};
int minn=100000000,ans2=0;
int hight[10000]={0};
int max_h=0;
void DFS(int root,int level){
if(max_h<level){
max_h=level;
}
if(Node[root].size()==0){
hashset[level]++;
}else{
for(int i=0;i<Node[root].size();i++){
DFS(Node[root][i],level+1);
}
}
}
int main()
{
int num,numfat;
scanf("%d %d",&num,&numfat);
for(int i=0; i<numfat; i++)
{
int father;
int n;
scanf("%d%d",&father,&n);
int x;
for(int j=0; j<n; j++)
{
scanf("%d",&x);
Node[father].push_back(x);
}
}
DFS(01,1);
int i;
for(i=1;i<max_h;i++){
printf("%d ",hashset[i]);
}
printf("%d\n",hashset[i]);
}