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:

2 1 01 1 02

Sample Output:

0 1

#include<iostream>
#include<algorithm>
#include<iomanip>
#include <ctype.h>
#include<string.h>
#include<string>
#include<cstring>
#include<stdio.h>
#include<stack>
#include<vector>
#include<queue>
# define INF 0x3f3f3f3f  //无穷大
using namespace std;


struct node {
    int level=0;
    vector<int> child;
};
node pedigree[101];
//层序遍历树,层序队列


int num[100] = {0};//存储每一层的叶节点数量
int max_level = 0;
void getlevel(int root){
    queue<int> n;//保存未遍历节点
    n.push(root);
    pedigree[root].level = 1;//根节点为第一层
    int level = 0;
    while (!n.empty()) {
        int temp = n.front();
        n.pop();//取一个出队列
        level = pedigree[temp].level;
        int count = pedigree[temp].child.size();
        for (int i = 0; i < count; i++) {//遍历改节点的每一个孩子,若为叶,则num[i]++;若为中间节点,则放入队列继续遍历
            int onechild = pedigree[temp].child[i];
            if (pedigree[onechild].child.size() == 0) {
                num[level + 1]++;
                max_level = level + 1;
            }
            else {
                n.push(onechild);
                pedigree[onechild].level = level + 1;
            }
        }
    }
}
int main() {
    int N;//家庭成员数量
    int M;//非叶节点数量
    cin >> N >> M;
    int k, father, child;
    for (int i = 0; i < M; i++) {
        cin >> father >> k;
        for (int j = 0; j < k; j++) {
            cin >> child;
            pedigree[father].child.push_back(child);
        }
    }
    if (N == 1)cout << 1;
    else {
        getlevel(1);
        cout << num[1];
        for (int i = 2; i <= max_level; i++) {
            cout << ' ' << num[i];
        }
    }
}