【PAT甲】1004 Counting Leaves (30分)(多叉树存储遍历,统计每层叶节点数)
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
- 点赞
- 收藏
- 关注作者
评论(0)