【PAT甲级】1004 Counting Leaves (30 分)(BFS)

题意:给出一棵树的点数N,输入M行,每行输入父亲节点An,儿子个数n,和a1,a2,...,an(儿子结点编号),从根节点层级向下依次输出当前层级叶子结点个数,用空格隔开。(0<N<100)

AAAAAccepted code:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 vector<int>v[107];
 4 queue<int>q;
 5 int tmp=0;
 6 int num=0;
 7 int cnt=0;
 8 int tim=0;
 9 int tt=0;
10 void BFS(){
11     int x=q.front();//队头元素调用
12     if(v[x].size())
13         for(auto it:v[x])//遍历x的所有儿子结点
14             if(v[it].size()==0)
15                 num++;//叶子结点++
16             else{
17                 q.push(it);//非叶子结点进队列
18                 cnt++;//非叶子结点计数器++
19             }
20     q.pop();//队头元素弹出
21     tim++;//处理次数++
22 }
23 int main(){
24     int n,m;
25     cin>>n>>m;
26     for(int i=1;i<=m;++i){
27         string fa;
28         cin>>fa;
29         int baba=(fa[0]-'0')*10+fa[1]-'0';
30         int x;
31         cin>>x;
32         string son;
33         for(int j=1;j<=x;++j){
34             cin>>son;
35             int erzi=(son[0]-'0')*10+son[1]-'0';
36             v[baba].push_back(erzi);
37         }
38     }
39     if(v[1].size()==0){
40         cout<<"1";
41         return 0;
42     }
43     else
44         cout<<"0";
45     for(auto it:v[1])
46         if(v[it].size()==0)
47             num++;//叶子结点个数
48         else{
49             q.push(it);//非叶子结点进队列
50             tt++;//非叶子结点个数
51         }
52     cout<<" "<<num;
53     num=0;
54     while(!q.empty()){
55         BFS();
56         if(tim==tt){//处理次数==非叶子结点个数,相当于这一层处理完了,开始统计这一层下一层有多少叶子结点
57             cout<<" "<<num;
58             tim=0;//处理次数初始化
59             num=0;//叶子结点个数初始化
60             tt=cnt;//非叶子结点个数更新为计数器
61             cnt=0;//非叶子节点计数器初始化
62         }
63     }
64     return 0;
65 }

 

 

 

posted @ 2019-07-18 14:40  sewage  阅读(196)  评论(0编辑  收藏  举报