zoukankan      html  css  js  c++  java
  • PAT(Advanced Level)A1004. Counting Leaves

    题意

    统计树中的每一层有多少叶子结点,要求逐层输出

    思路

    • 逐层输出,刚好层序遍历是逐层扩展,所以我就直接用BFS了

    代码

    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <vector>
    #include <queue>
    #include <math.h>
    using namespace std;
    int N, M;
    vector<int> tree[110];
    vector<int> ans;
    void bfs(int st)
    {
        queue<int> q;
        q.push(st);
        while(!q.empty())
        {
            int size = q.size();
            int count = 0;
            for(int i=0;i<size;i++)
            {
                auto cur = q.front();
                q.pop();
                if(tree[cur].size() == 0)       //叶子结点
                    count++;
                for(int j=0;j<tree[cur].size();j++)
                    q.push(tree[cur][j]);
            }
            ans.emplace_back(count);
        }
    }
    int main()
    {
        cin >> N >> M;
        int id, t, cnt;
        for(int i=0;i<M;i++)
        {
            cin >> id;
            cin >> cnt;
            for(int j=0;j<cnt;j++)
            {
                cin >> t;
                tree[id].emplace_back(t);
            }
        }
        bfs(1);
        for(int i=0;i<ans.size();i++)
            i == ans.size() - 1 ? cout << ans[i]: cout << ans[i] << " ";
        return 0;
    }
    
    
  • 相关阅读:
    枚举-完美立方
    list
    undefined reference to `typeinfo for xxx 报错
    bubble排序
    Iframe跨域传值
    Iframe------父子页面传值
    LDAP 概念
    覆盖equals()要覆盖HashCode()
    HashSet和TreeSet的实现与原理
    jvm调优
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/13773145.html
Copyright © 2011-2022 走看看