PAT甲级1004 Counting Leaves (30分)

原题:在这里插入图片描述
题目大意:一个树,n个节点,m个非叶节点,求出每一层叶节点数。
源代码:

#include<iostream>
#include<queue>
using namespace std;
int tree[105][105]; //规模不大,直接用数组存树
int tchild[105];    //每个节点的孩子数
int vis[105];       //访问标志
int n, m;           //n结点数,m非叶结点数
queue<int> q;      //辅助队列
int cs = 0;           //记录层数
queue<int> childnum;
int main(){
    cin>>n>>m;
    for(int i = 0; i < m; i ++){
        int id, k;
        cin>>id>>k;
        tchild[id] = k;
        for(int j = 0; j < k; j ++){
            int tmp;
            cin>>tmp;
            tree[id][tmp] = 1;
        }
    }
    if(tchild[1] == 0){             //根节点是叶节点
        cout<<"0";
        return 0;
    }
    q.push(1);
    vis[1] = 1;
    childnum.push(0);               //根节点不是叶节点
    int cnum = tchild[1];
    int nextnum = 0;
    int leafnum = 0;
    int cnow = 0;
    while(!q.empty()){
        int p = q.front();
        q.pop();
        for(int i = 1; i <= n; i ++){
            if(tree[p][i] == 1 && vis[i] == 0){
                nextnum += tchild[i];
                if(tchild[i] == 0)
                    leafnum ++;
                cnow ++;
                q.push(i);
                vis[i] = 1;
                if(cnow == cnum){
                    cnow = 0;
                    cnum = nextnum;
                    nextnum = 0;
                    cs ++;
                    childnum.push(leafnum);
                    leafnum = 0;
                }
                    
            }
        }
    }
    while(!childnum.empty()){
        int p = childnum.front();
        childnum.pop();
        cout<<p;
        if(!childnum.empty())
            cout<<" ";
    }
    return 0;
}

已AC:在这里插入图片描述

易失分点:
1.只有根节点时输出1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值