原题链接
这道题本质就是在求每层叶子结点个数
DFS用惯了BFS用起来有点困难 还是要多练
DFS:
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
const int maxn = 100010;
//求每层叶子结点个数
vector<int> Node[maxn];
int n,m;
int hashtable[maxn] = {0}; //记录第i层叶子结点有多少个
int max_h = 0;
void DFS(int index, int level)
{
max_h = max(max_h,level); //标记最深层数
if(Node[index].size() == 0)
{
hashtable[level]++;
return;
}
for(int i = 0; i < Node[index].size(); i++)
{
DFS(Node[index][i],level + 1);
}
}
int main()
{
cin >> n >> m;
int id,k,x;
for(int i = 0; i < m; i++)
{
cin >> id >> k;
for(int j = 0; j < k; j++)
{
cin >> x;
Node[id].push_back(x);
}
}
DFS(1,1);
cout << hashtable[1];
for(int i = 2; i <= max_h; i++)
{
cout << " " << hashtable[i];
}
return 0;
}
BFS:
#include <iostream>
#include <vector>
#include <math.h>
#include <queue>
using namespace std;
const int maxn = 100010;
//求每层叶子结点个数
vector<int> Node[maxn];
int n,m;
int max_h = 0;
int h[maxn];//各个节点所在的层数
int leaf[maxn];//各层所有的节点数
void BFS()
{
queue<int> q;
q.push(1);
while(!q.empty())
{
int now = q.front();
q.pop();
max_h = max(max_h, h[now]);
if(Node[now].size() == 0) leaf[h[now]]++;
for(int i = 0; i < Node[now].size(); i++)
{
h[Node[now][i]] = h[now] + 1;
q.push(Node[now][i]);
}
}
}
int main()
{
cin >> n >> m;
int id,k,x;
for(int i = 0; i < m; i++)
{
cin >> id >> k;
for(int j = 0; j < k; j++)
{
cin >> x;
Node[id].push_back(x);
}
}
BFS();
cout << leaf[0];
for(int i = 1; i <= max_h; i++)
{
cout << " " << leaf[i];
}
return 0;
}