BFS——PAT 甲级 1004

PAT 甲级 1004

给出一棵树,问每一层都有多少个叶子节点

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#define M 200000010
#define INF 0x3f3f3f3f
using namespace std;

vector<int> v[105];
int deep[105];
int ans[105];

int main()
{
    int n,m;
    cin >> n >> m;
    for(int i=1; i<=m; i++){
        int x,k,y;
        cin >> x >> k;
        for(int j=1; j<=k; j++){
            cin >> y;
            v[x].push_back(y);
        
        }
    }
    deep[1] = 1;
    queue<int>q;
    q.push(1);
    int mx = 1;
    while(!q.empty()){
        int fa = q.front();
        q.pop();
        if(v[fa].empty()){
            ans[deep[fa]]++;
            continue;
        }
        for(int i=0; i<v[fa].size(); i++){
            int son = v[fa][i];
            deep[son] = deep[fa] + 1;
            mx = max(mx,deep[son]);
            q.push(son);
        }
        
    }
    for(int i=1; i<=mx; i++){
        cout << ans[i] << " ";
    }
    return 0;
}

发布了30 篇原创文章 · 获赞 0 · 访问量 677

猜你喜欢

转载自blog.csdn.net/jhckii/article/details/104121324