【树】1004 Counting Leaves (30分)数叶子节点

原题链接

DFS + 邻接表(数组模拟)
邻接表:对每一个点开一个单链表

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 110;

int n, m; //节点总数,内部节点数量
int h[N], e[N], ne[N], idx;
int cnt[N]; //存每一层的叶子节点数
int max_depth; //最大层数
void add(int a, int b)  //在a这个结点所在的单链表插入结点b,表示a有个child是b
{
	ne[idx] = h[a];
	h[a] = idx;
	e[idx] = b;
	idx ++;
}

void dfs(int u, int depth)
{
	if(h[u] == -1)  //当前结点是叶子节点
	{
		cnt[depth]++;
		max_depth = max(max_depth, depth);
		return;
	}
	for(int i = h[u]; i != -1; i = ne[i])//若不是叶子节点则遍历子节点
	{
		dfs(e[i], depth + 1);
	}
	
}
int main()
{
	cin >> n >> m;
	memset(h, -1, sizeof h); //邻接表初始化
	for(int i = 0; i < m; i++)
	{
		int id, k;
		cin >> id >> k;
		while(k--) //读入k个孩子
		{
			int son;
			cin >> son;
			add(id, son); //存入邻接表
		}
	}
	dfs(1, 0); //从根节点(1号点)开始搜深度为0

	cout << cnt[0];
	for(int i = 1; i <= max_depth; i++)
		cout << " " << cnt[i];
	cout << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值