PAT (Advanced) 1004. Counting Leaves (30)
来源:互联网 发布:电脑卸载软件推荐 编辑:程序博客网 时间:2024/05/22 00:17
原题:1004. Counting Leaves (30)
典型的树的层序遍历问题,用层序遍历或者广度优先搜索方法解决:
1. 用vector动态记录每个点的孩子的数目。
2.赋予相应的层号,在遍历中每当层号发生变化,说明该层遍历结束,应记录统计值。
c++代码如下:
#include<cstdio>#include<vector>#include<algorithm>#include<queue>using namespace std;const int maxn = 110;vector<int> ans; // 记录各层的答案struct Node{ int level; vector<int> child;} node[maxn]; //采用静态树void levelOrder(){ queue<Node> Q; Q.push(node[1]); node[1].level = 1; int cnt = 0; //记录当前层的无孩子结点数目 int level = 0; //当前的层数 while(!Q.empty()) { Node top = Q.front(); Q.pop(); if(top.level != level) //层数发生变化 { level = top.level; ans.push_back(cnt); cnt = 0; } if(top.child.empty()) //当前结点无孩子 { cnt++; } for(int i = 0; i < top.child.size(); i++) { node[top.child[i]].level = top.level + 1; Q.push(node[top.child[i]]); } } ans.push_back(cnt); //注意将最后一次的统计结果放入答案中}int main(){ int n, m; while(scanf("%d%d", &n, &m) != EOF) { //输入 for(int i = 0; i < m; i++) { int k, id; scanf("%d%d", &id, &k); for(int i = 0; i < k; i++) { int child; scanf("%d", &child); node[id].child.push_back(child); } } levelOrder(); for(int i = 0; i < ans.size(); i++) { if(i == 0) printf("%d", ans[i]); else printf(" %d", ans[i]); } printf("\n"); } return 0;}
阅读全文
0 0
- 【PAT Advanced Level】1004. Counting Leaves (30)
- PAT (Advanced Level) 1004. Counting Leaves (30)
- 【PAT】【Advanced Level】1004. Counting Leaves (30)
- PAT (Advanced) 1004. Counting Leaves (30)
- 浙大PAT (Advanced Level) Practise 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)——PAT (Advanced Level) Practise
- PAT (Advanced Level) Practise 1004. Counting Leaves (30)
- 浙大PAT (Advanced Level) Practise 1004. Counting Leaves (30)
- PAT (Advanced Level) 1004. Counting Leaves (30) 解题报告
- PAT (Advanced Level) Practise 1004. Counting Leaves (30)
- PAT Advanced 1004. Counting Leaves (30) (C语言实现)
- PAT (Advanced Level) Practise 1004. Counting Leaves (30)
- 浙大 PAT Advanced level 1004. Counting Leaves
- 1004. Counting Leaves (30)-PAT
- pat 1004. Counting Leaves (30)
- 【PAT】1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- unity 读取手机电量
- Android GLSurfaceView.Renderer 类 onDrawFrame 方法的刷新机制
- Java基础之集合框架所对应的数据结构
- 小学期 修剪草坪
- CodeForces Gym 101190简要题解
- PAT (Advanced) 1004. Counting Leaves (30)
- LA4329:Ping pong(树状数组入门)
- 【java字符串格式化】String.format()使用方法
- Python实现套接字(Socket)的客户端(Client)
- JavaScript split() 方法
- SpringMVC与Ajax数据交互
- ssh框架hibernate篇1
- cript toLocaleString() 方法
- uva1225 计数