zoukankan      html  css  js  c++  java
  • 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;
    }
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    几个 vim 的块操作命令
    图灵社区 : 阅读 : 谁说Vim不是IDE?(三)
    google.sg
    Vim 配置详解_wuyang
    Vim 配置详解_wuyang
    不忘本~结构
    刚刚做了一个菜单导航变亮的效果,共享一下吧!
    不忘本~静态构造函数
    数据结构~时间复杂度和空间复杂度
    数据结构~在页面上渲染树型结构
  • 原文地址:https://www.cnblogs.com/itdef/p/14395430.html
Copyright © 2011-2022 走看看