题意
给出一棵树,要求输出每一层的叶子节点的数量,叶子节点的定义为没有子节点的节点。
这题不难,不过很久不写了就写个博客记录一下吧。
#include "bits/stdc++.h"
using namespace std;
const int maxn = 110;
vector<int> nodes[maxn];
map<int,int> ans;
int vis[maxn];
void dfs(int id,int depth){
if(vis[id]) {
return;
}
vis[id] = 1;
if(nodes[id].empty()) ans[depth] ++;
else ans[depth] = ans[depth];
for(int t:nodes[id]){
if(vis[t]) continue;
dfs(t,depth+1);
}
}
int main() {
//freopen("input.txt","r",stdin);
int n,m; cin >> n >> m;
for(int i=0;i<m;i++){
int id,k; scanf("%d%d",&id,&k);
for(int j=0;j<k;j++){
int cid; scanf("%d",&cid); nodes[id].push_back(cid);
}
}
int root = 1;
dfs(1,0);
bool blank = false;
for(auto& item:ans){
if(blank) cout << " ";
else blank = true;
cout << item.second;
}
return 0;
}
input:
2 1
01 1 02
output:
0 1