【PAT甲】1004 Counting Leaves (30分)(多叉树存储遍历,统计每层叶节点数)

举报
小哈里 发表于 2022/05/11 01:26:12 2022/05/11
【摘要】 problem 1004 Counting Leaves (30分) A family hierarchy is usually presented by a pedigree tree. Your j...

problem

1004 Counting Leaves (30分)
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input Specification:
Each input file contains one test case. Each case starts with a line containing 0<N<100, the number of nodes in a tree, and M (<N), the number of non-leaf nodes. Then M lines follow, each in the format:

ID K ID[1] ID[2] … ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID’s of its children. For the sake of simplicity, let us fix the root ID to be 01.

The input ends with N being 0. That case must NOT be processed.

Output Specification:
For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output 0 1 in a line.

Sample Input:
2 1
01 1 02
Sample Output:
0 1

  • 一个家族中假设有n名成员,其中m个人有孩子,分别给出这m个人孩子的名单
  • 求每一辈有几个成员是没有儿子的
  • 即给出一棵树(共n点,m个非叶节点及其子节点),问每一层各有多少个叶子结点

solution

  • 多叉树的存储和遍历:一是链表指针结构强行乱搞,二是邻接表记录每个节点的子节点,vectorG[110]或者Tree[110][10]都可以。
  • 用book[i]表示每一层的叶子节点个数,dfs遍历一遍树并记录当前depth,每访问到一个叶子节点的时候都更新book[depth]++;
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int>Tree[110];
int book[110], maxdep;
void dfs(int node, int dep){
	if(Tree[node].size()==0){
		book[dep]++;
		maxdep = max(maxdep,dep);
		return ;
	}
	for(int i = 0; i < Tree[node].size(); i++)
		dfs(Tree[node][i], dep+1);
}
int main(){
	int n, m;
	cin>>n>>m;
	for(int i = 0; i < m; i++){
		int node, k;
		cin>>node>>k;
		for(int j = 0; j < k; j++){
			int c;  cin>>c;
			Tree[node].push_back(c);
		}
	}
	dfs(1,0);//从根节点开始遍历,当前深度为0
	cout<<book[0];
	for(int i = 1; i <= maxdep; i++)
		cout<<" "<<book[i];
	return 0;
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

文章来源: gwj1314.blog.csdn.net,作者:小哈里,版权归原作者所有,如需转载,请联系作者。

原文链接:gwj1314.blog.csdn.net/article/details/108410691

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。