牛客PAT甲级练习题 1016 Counting Leaves (30)

题意

给出一棵树,要求输出每一层的叶子节点的数量,叶子节点的定义为没有子节点的节点。
这题不难,不过很久不写了就写个博客记录一下吧。

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值