PAT 甲级 1004 Counting Leaves
地址 https://pintia.cn/problem-sets/994805342720868352/problems/994805521431773184
一个多叉树的题目 给与我们两个整数N M 整数 N 表示树中结点总数 ,整数 M 表示非叶子结点数。根节点数序号01 接下来M行 每行输入一个节点和该节点的子节点 格式如下 ID K ID[1] ID[2] ... ID[K] ID表示当前节点 K表示该节点的子节点的数目 后面一次是子节点的ID 以空格间隔 要求我们输出 从上往下 树的每一层有多少叶子结点 以空格间隔
示例1 Sample Input: 2 1 01 1 02 Sample Output: 0 1
图例1
示例2 Sample Input: 5 3 01 2 02 03 02 1 05 03 1 04 Sample Output: 0 0 2
图例2
解答
考虑到是一层层的计算有无叶子结点。开始是尝试使用bfs 广度优先搜索
依照层次逐步向下搜索,搜索过程中是带上了当前节点的层级,如果发现层级数有变化,
那么就可以将上一层级的统计出叶子结点放入答案.
#include <iostream> #include <map> #include <queue> #include <vector> #include <algorithm> using namespace std; const int N = 150; map<int, vector<int>> mm; int n, m; vector<int> ans; void bfs(int x) { queue<pair<int, int>> q; int currLevel = 1; int currCount = 0; q.push({ x,currLevel }); while (!q.empty()) { int curr = q.front().first; int level = q.front().second; q.pop(); if (level != currLevel) { ans.push_back(currCount); currLevel = level; currCount = 0; } if(mm[curr].size()==0) { currCount++; } for (int i = 0; i < mm[curr].size(); i++) { int next = mm[curr][i]; q.push({ next,level + 1 }); } } ans.push_back(currCount); return; } int main() { cin >> n >> m; for (int i = 0; i < m; i++) { int curr; int count; int t; cin >> curr >> count; for (int j = 0; j < count; j++) { cin >> t; mm[curr].push_back(t); } } if (m == 0) { cout << 1 << endl; return 0; } bfs(1); for (int i = 0; i < ans.size(); i++) { cout << ans[i] ; if(i != ans.size()-1){ cout << " "; } } cout << endl; return 0; }
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话