【PAT甲级】 1004 Counting Leaves
原题
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 1:
2 1
01 1 02
Sample Output 1:
0 1
思路
题目要求
给出树中节点数和非叶节点数;同时给出非叶节点ID,该节点的子节点数及子节点ID;求出各层的叶节点数。
题目分析
- 输出最后无空格;
- 输出为一行;
- 根节点默认为01;
- ID为两位数;
- 想到树的遍历,输出按照行,层序遍历;
易错点
- ID可以定义为int类型,像01会自动转换成1;(这是自己尝试了一下)
- 该题只说了是数,并没有说是二叉树,故子节点数可能大于2;
参考代码如下
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
vector<int> v[100];//这是二维数组
int maxdepth = -1;//按层输出要知道深度
int sum[100];//存储每层的叶节点数
void j1004(int depth,int num){
if(v[num].size()==0){
sum[depth]++;
maxdepth = maxdepth>depth?maxdepth:depth;
return ;
}
for(int i=0;i<v[num].size();i++){
j1004(depth+1,v[num][i]);//子节点,是下一层
}
}
int main(){
memset(sum,0,sizeof(sum));
int n,m;
scanf("%d %d",&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 id1;
scanf("%d",&id1);
v[id].push_back(id1);
}
}
j1004(0,1);
printf("%d",sum[0]);
for(int i=1;i<=maxdepth;i++){
printf(" %d",sum[i]);
}
// 如果是先把前面的输出,用printf("%d ",sum[i]);再输出最后一个,有可能出现maxdepth就是0的情况
}
附
- 网上的参考代码很多;
- 以上仅是用来记录我个人的想法和答题方式;
- 仅为入门选手,如有错误或者更好的方法欢迎指正与探讨;
- 该题也可以用bfs去做