PAT-A 真题- 1004. Counting Leaves

发布于 / PAT-甲级 / 0 条评论

原题干:

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

题目大意:

找出谁没有孩子!

输入第一行给出 N(树的节点总数)和 M(树的非叶节点数量)接着给出M行数据,每一行数据的格式为:

ID(编号)  K(有几个孩子)  ID[1](第1个孩子) ... ID[K](直到第K个孩子)

ID都是两位数(例如21,06等等)为了简便,定义根节点的编号为01。

要求按照每一层的顺序,从根节点开始,找到每一层的叶子结点个数。

然后依次输出,使用一个空格分离。末尾不得有多余的空格。

这道题是一道考察树的问题,我们可以使用静态二叉树,然后按照题目要求读入二叉树,使用BFS算法层序遍历二叉树即可。遍历的时候要记得记录层次信息,并且要计算树的高度,将结果存入数组中,然后根据高度遍历输出结果数组即可。代码如下:

#include <iostream>
#include <vector>
#include <queue>
#define MAXN 110
using namespace std;
vector<int> tree[MAXN];
int result[MAXN] = {0};
int MAX_layer = 0;
typedef struct{
  int ID;
  int layer;
} node;
/*深度优先搜索方法*/
void BFS(int root){
  queue<node> Q;
  Q.push({root, 0});
  while(!Q.empty()){
    node top = Q.front();
    Q.pop();
    //如果发现更大的层次,更新MAX_layer 
    if(top.layer > MAX_layer) MAX_layer = top.layer;
    //如果本节点的子节点为空,result数组在本层次的下标++ 
    if(tree[top.ID].size() == 0) result[top.layer]++;
    //如果本节点非空,将子节点全部压入队列
    if(tree[top.ID].size() != 0){
      for(int i = 0; i < tree[top.ID].size(); i++){
        int new_id = tree[top.ID][i], new_layer = top.layer + 1;
        Q.push({new_id, new_layer});
      }
    }
  } 
}

int main(){
  int N, M;
  //读入N和M 
  cin >> N >> M;
  for(int i = 0; i < M; i++){
    int ID, cnt, tmp;
    //读入整棵树 
    cin >> ID >> cnt;
    for(int j = 0; j < cnt; j++){ 
      cin >> tmp;
      tree[ID].push_back(tmp);
    }
  }
  BFS(1);
  for(int i = 0; i <= MAX_layer; i++){
    cout << result[i]; 
    if(i != MAX_layer) cout << " ";
  }
  cout << endl;
  return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题- 1004. Counting Leaves
目前还没有评论,快来抢沙发吧~