PAT 甲级 1004 Counting Leaves

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

一个多叉树的题目

给与我们两个整数N  M

整数 N 表示树中结点总数 ,整数 M 表示非叶子结点数。根节点数序号01
接下来M行 每行输入一个节点和该节点的子节点

格式如下 ID K ID[1] ID[2] ... ID[K]

ID表示当前节点  K表示该节点的子节点的数目 后面一次是子节点的ID 以空格间隔

要求我们输出 从上往下 树的每一层有多少叶子结点 以空格间隔
示例1 

Sample Input:
2 1
01 1 02
Sample Output:
0 1

图例1 

 

 

示例2
Sample Input:
5 3
01 2 02 03
02 1 05
03 1 04
Sample Output:
0 0 2

图例2

 

 

 

解答

考虑到是一层层的计算有无叶子结点。开始是尝试使用bfs 广度优先搜索

依照层次逐步向下搜索,搜索过程中是带上了当前节点的层级,如果发现层级数有变化,

那么就可以将上一层级的统计出叶子结点放入答案.

#include <iostream>
#include <map>
#include <queue>
#include <vector>
#include <algorithm>

using namespace std;
const int N = 150;
map<int, vector<int>> mm;
int n, m;
vector<int> ans;

void bfs(int x) {
    queue<pair<int, int>> q;
    int currLevel = 1;
    int currCount = 0;
    q.push({ x,currLevel });

    while (!q.empty()) {
        int curr = q.front().first;
        int level = q.front().second;
        q.pop();

        if (level != currLevel) {
            ans.push_back(currCount);
            currLevel = level;
            currCount = 0;
        }
        if(mm[curr].size()==0) { currCount++; }

        for (int i = 0; i < mm[curr].size(); i++) {
            int next = mm[curr][i];
            q.push({ next,level + 1 });
        }

    }
    ans.push_back(currCount);
    return;
}

int main()
{
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int curr; int count; int t;
        cin >> curr >> count;
        for (int j = 0; j < count; j++) {
            cin >> t;
            mm[curr].push_back(t);
        }
    }
    if (m == 0) {
        cout << 1 << endl;
        return 0;
    }
    bfs(1);
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] ;
        if(i != ans.size()-1){
            cout << " ";
        }
    }
    cout << endl;

    return 0;
}

 

posted on 2021-02-10 12:10  itdef  阅读(69)  评论(0编辑  收藏  举报

导航