PAT甲级-1004 Counting Leaves (30)(30 分)-树-BFS

1004 Counting Leaves (30)(30 分)

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

https://pintia.cn/problem-sets/994805342720868352/problems/994805521431773184

思路:用广度遍历,但稍微修改下,每次不是处理一个结点,而是处理一层结点,可用变量记录当前的层数,然后就可以数出当前层数的叶结点。

/*c++代码*/
#include<bits/stdc++.h>
using namespace std;

const int maxn = 100 + 10;
int n,en; //n=点数,en=边数

vector<int> no[maxn]; //存储某结点的孩子
int leave[maxn];  //某层的叶结点数目
int cur_dep,cur_num; //当前层,当前层的结点数

/*结点按照层次分批进队,并记录该层次的叶结点数*/
void bfs() {
    queue<int> q;
    q.push(1);  //根结点入队
    cur_dep = -1;  
    while (q.size()) {  //只要队列非空,就继续处理下一层的结点
        cur_num = q.size(); //当前层的结点数
        cur_dep++; //当前层,根结点位于0层
        
        /*将当前层结点的孩子们都入队*/
        for (int i = 0; i < cur_num; i++) {
            int top = q.front(); q.pop();
            if (no[top].size()) { //队首结点top有孩子,则循环入队
                for (int j = 0; j < no[top].size(); j++) {
                    q.push(no[top][j]);
                }
            }
            else {  //队首结点top无孩子,则其为叶结点,当前层的叶结点数增加
                leave[cur_dep]++;
            }
        }
    }
}

int main() {
  
    /*接收数据*/
    scanf("%d %d", &n,&en);
    int id, k,in1;
    for (int i = 0; i < en; i++) {
        scanf("%d %d", &id,&k);
        for (int j = 0; j < k; j++) {
            scanf("%d", &in1);
            no[id].push_back(in1);
        }
    }
    
    /*广度遍历*/
    bfs();
    
    /*打印0-最后一层的叶结点数目*/
    printf("%d",leave[0]);
    for (int i = 1; i <= cur_dep; i++) {
        printf(" %d", leave[i]);
    }

    return 0;
}




猜你喜欢

转载自blog.csdn.net/yeziand01/article/details/80765462