pat甲级打卡-1004 Counting Leaves (测试点3未通过)

1004 Counting Leaves (30 分)

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

测试点3一直过不去不清楚为什么,检查了很久没检查出来,不过bfs记录层数还是很重要的。好题一道

#include<bits/stdc++.h>
using namespace std;
const int N=101;
//建树
int n,m;
int ne[N],idx,e[N],h[N];
int depth[N];
int layer[N]; //存每层的叶节点数量
bool haveChild[N];

bool st[N];
void add(int a,int b){//a-->b有向边
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
//难点如何记录bfs的level?
void bfs(int u){
    memset(layer,0,sizeof layer);
    queue<int> q;
    q.push(u);
    depth[u]=1;
    int maxdepth=0;
    while(q.size()){
        int t=q.front();
        q.pop();
        bool haschild=false;
        for(int i=h[t];i!=-1;i=ne[i]){ //遍历t结点的子节点
            int j=e[i]; //取结点号
            q.push(j);//入队
            depth[j]=depth[t]+1;
            maxdepth=max(depth[j],maxdepth);
            haschild=true;
        }
        if(!haschild) layer[depth[t]]++;
        
    }
    
    for(int i=1;i<=maxdepth;i++){
        if(i!=1)  cout<<" ";
        cout<<layer[i];
    }
    
}
// 调试代码,查看树的结构是否正确,没实际运行
void dfs(int u){
    cout<<u<<" ";
    st[u]=true;
    for(int i=h[u];i!=-1;i=ne[i]){
        int j=e[i];
        if(!st[j]){
            dfs(j);
        } 
    }
}
int main(){
    memset(h,-1,sizeof h);
    
    cin>>n>>m;
    for(int i=0;i<m;i++){
        int fa,k;
        cin>>fa>>k;
        while(k--){
            int t;
            cin>>t;
            add(fa,t); //fa-->t 
            //haveChild[fa]=true;
        }
    }    
    bfs(1);//puts("");
    //dfs(1);    
   // for(int i=1;i<=5;i++) cout<<depth[i]<<" ";
    return 0;
}

posted @ 2022-04-21 00:04  秋月桐  阅读(57)  评论(0编辑  收藏  举报