注意:允许转载,但转载请注明作者和出处
最重要:单链表和邻接表怎么用数组写
本题就涉及到了,不多展开描述
AcWing 1476. 数叶子结点
题目
答案
#include <iostream>
#include <cstring>
using namespace std;
const int N = 110;
int h[N], e[N], ne[N], idx;
int leaf[N], depth = 0, max_depth = -1;
void add(int a, int b) // a为father,b为son
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
void dfs(int root, int depth)
{
if (h[root] == -1) // root为叶子结点
{
leaf[depth] ++;
max_depth = max(max_depth, depth);
return;
}
for (int i = h[root]; i != -1; i = ne[i])
{
int j = e[i];
dfs(j, depth + 1);
}
}
int main()
{
int n, m;
cin >> n >> m;
memset(h, -1, sizeof h);
while (m --)
{
int father, k;
cin >> father >> k;
while (k --)
{
int son;
cin >> son;
add(father, son);
}
}
dfs(1, depth);
for (int i = 0; i <= max_depth; i ++)
cout << leaf[i] << ' ';
puts("");
return 0;
}