首页 > 代码库 > PAT甲题题解-1004. Counting Leaves (30)-统计每层叶子节点个数+dfs

PAT甲题题解-1004. Counting Leaves (30)-统计每层叶子节点个数+dfs

统计每层的叶子节点个数
建树,然后dfs即可

技术分享
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
/*
统计每层的叶子节点个数
建树,然后dfs即可
*/
const int maxn=105;
int n,m;
int layer[maxn]; //统计每层的叶子节点个数
int maxlayer=0;
vector<int>node[maxn];

void dfs(int u,int level){
    int num=node[u].size();
    if(num==0){
        layer[level]++;
        if(level>maxlayer)
            maxlayer=level;
        return;
    }
    for(int i=0;i<node[u].size();i++){
        dfs(node[u][i],level+1);
    }
}
int main()
{
    memset(layer,0,sizeof(layer));
    scanf("%d %d",&n,&m);
    int u,v,k;
    for(int i=0;i<m;i++){
        scanf("%d %d",&u,&k);
        for(int i=0;i<k;i++){
            scanf("%d",&v);
            node[u].push_back(v);
        }
    }
    dfs(1,0);
    printf("%d",layer[0]);
    for(int i=1;i<=maxlayer;i++)
        printf(" %d",layer[i]);
    return 0;
}
View Code

 

PAT甲题题解-1004. Counting Leaves (30)-统计每层叶子节点个数+dfs