DFS + 邻接表(数组模拟)
邻接表:对每一个点开一个单链表
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 110;
int n, m; //节点总数,内部节点数量
int h[N], e[N], ne[N], idx;
int cnt[N]; //存每一层的叶子节点数
int max_depth; //最大层数
void add(int a, int b) //在a这个结点所在的单链表插入结点b,表示a有个child是b
{
ne[idx] = h[a];
h[a] = idx;
e[idx] = b;
idx ++;
}
void dfs(int u, int depth)
{
if(h[u] == -1) //当前结点是叶子节点
{
cnt[depth]++;
max_depth = max(max_depth, depth);
return;
}
for(int i = h[u]; i != -1; i = ne[i])//若不是叶子节点则遍历子节点
{
dfs(e[i], depth + 1);
}
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h); //邻接表初始化
for(int i = 0; i < m; i++)
{
int id, k;
cin >> id >> k;
while(k--) //读入k个孩子
{
int son;
cin >> son;
add(id, son); //存入邻接表
}
}
dfs(1, 0); //从根节点(1号点)开始搜深度为0
cout << cnt[0];
for(int i = 1; i <= max_depth; i++)
cout << " " << cnt[i];
cout << endl;
return 0;
}