A1004 Counting Leaves [dfs]
程序员文章站
2022-06-11 15:08:52
...
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn = 110;
vector<int>node[maxn];
int hashtable[maxn];//叶子节点
int maxLevel = -1;
void dfs(int index,int level)
{
if (node[index].size() == 0)
{
hashtable[level]++;
if (level > maxLevel)
maxLevel = level;
return;
}
for (int i = 0; i < node[index].size(); i++)
{
dfs(node[index][i], level + 1);
}
}
int main()
{
int n, m;
int root, k, child;
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> root >> k;
for (int j = 0; j < k; j++)
{
cin >> child;
node[root].push_back(child);
}
}
dfs(1, 1);
cout << hashtable[1];
for (int i = 2; i <= maxLevel; i++)
{
cout << " " << hashtable[i];
}
}