1004. Counting Leaves (30)

题目链接:http://www.patest.cn/contests/pat-a-practise/1004

题目:




  
  
  
  
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input

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.

Output

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

分析:

题目是说有一个类似家庭族谱的东西,开始的时候是由一个根节点(编号定为01),让你找出每一代中没有孩子的节点个数。

抽象出来就是对于一个多叉树,找出每一层的叶子节点的数目

*注意点

1)因为是根据每一层来统计叶子节点,所以需要一个高度的字段

2)输入的数据可能是乱序的,不一定是按照从根到叶子的顺序

AC的代码:

#include<stdio.h>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
struct Node{
 int parent;
 int high;
 bool has_child;//如果有孩子,则说明不是叶子节点
}node[102];//节点结构体,包括父母,高度,和是否有孩子
int high_max;//最大高度(深度)
int my_count[102];//记录每层高度的叶子节点数目
int find_high(int i){
 if(node[node[i].parent].high == 0)
  return node[i].high = find_high(node[i].parent) + 1;
 else
  return node[i].high = node[node[i].parent].high + 1;
}//递归找出节点的高度
int main(void){
 int i,j,n,m;
 while(scanf("%d%d",&n,&m) != EOF){
  for(i = 1; i <= n; i ++){
   node[i].parent = 0;
   node[i].high = 0;
   node[i].has_child = false;
   my_count[i] = 0;
  }//init()初始化
  for(i = 1; i <= m; i ++){
   int k,a,b;
   scanf("%d%d",&a,&k);
   node[a].has_child = true;
   for(j = 1; j <= k; j ++){
    scanf("%d",&b);
    node[b].parent = a;
   }
  }//接收输入,记录各节点
  node[1].high = 1;//初始化,不要忘了
  for(i = 2; i <= n; i ++){
   find_high(i);
  }//因为输入的数据可能是乱序的,所以需要在数据输完之后进行查找高度的操作
  for(i = 1; i <= n; i ++){
   if(high_max < node[i].high)
    high_max = node[i].high;
  }//找到最大的高度(深度)
  for(i = 1; i <= n; i ++){
   if(node[i].has_child == false){
    my_count[node[i].high] ++;
   }
  }找到各层中高度的叶子节点数目
  for(i = 1; i <= high_max; i++){
   if(i == high_max)
    printf("%d", my_count[i]);
   else
    printf("%d ", my_count[i]);
  }
 }//格式化输出
 return 0;
}
1004. Counting Leaves (30)_第1张图片


P.S:

对于这一题,可以用这样的方法,方便理解。不过实际上,对于层序遍历或树的节点的构造,应该要有更正规的方法(前者用queue,后者用Node *),这在以后会提到。


——Apie陈小旭

你可能感兴趣的:(1004. Counting Leaves (30))