PAT A1004 Counting Leaves (30分)(层序遍历)

#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
const int N = 110;
int n;
struct node{
    int layer;
    bool isleaf = true;
    vector<int> child;
}Node[N];
int leafinlayer[N];
int h=0;
void layerorder(int root){
    queue<int> q;
    q.push(root);
    Node[root].layer=0;
    while(q.empty()==false){
        int front = q.front();
        q.pop();
        if(Node[front].isleaf==true){
            if(h<Node[front].layer){
                h = Node[front].layer;
            }
            leafinlayer[Node[front].layer]++;
        }else{
            for(int i = 0;i<Node[front].child.size();i++){
                int id = Node[front].child[i];
                q.push(id);
                Node[id].layer = Node[front].layer+1;
            }
        }
        
    }
    return;
}
int main(){
    int m;
    scanf("%d %d",&n,&m);
    for(int i = 0;i<m;i++){
        int id,childnum;
        scanf("%d %d",&id,&childnum);
        Node[id].isleaf=false;
        for(int j = 0;j<childnum;j++){
            int childid;
            scanf("%d",&childid);
            Node[id].child.push_back(childid);
        }
    }
    layerorder(1);//root默认为1
    for(int i = 0;i<=h;i++){
        printf("%d",leafinlayer[i]);
        if(i!=h){
            printf(" ");
        }
    }
}
posted @ 2020-09-09 17:55  是水泵呢  阅读(63)  评论(0编辑  收藏  举报