1004. Counting Leaves (30) PAT+BFS
来源:互联网 发布:mssql查询分析器下载 编辑:程序博客网 时间:2024/06/14 19:29
Input
Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format:
ID K ID[1] ID[2] ... ID[K]where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.
Output
For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.
The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output "0 1" in a line.
Sample Input2 101 1 02Sample Output
0 1
C++代码:
#include <iostream>#include <vector>#include <queue>int n, m;std::vector<std::vector<int>> edge;std::vector<int> BFS(int s){std::queue<std::pair<int,int>> q;q.push(std::make_pair(s, 0));int cur_step = 0;std::vector<int> ans;int cnt = 0;while (!q.empty()){int u = q.front().first;int step = q.front().second;q.pop();if(step > cur_step){ans.push_back(cnt);cnt = 0;cur_step = step;}if(edge[u].size() == 0) cnt++;for (int i = 0; i < edge[u].size(); ++i){int v = edge[u][i];q.push(std::make_pair(v, step+1));}}ans.push_back(cnt);return ans;}int main(){while (scanf("%d%d",&n,&m)!=EOF){//input edgesedge.clear();edge.resize(n+1);while (m--){int a, k;scanf("%d%d", &a,&k);while (k--){int b;scanf("%d",&b);edge[a].push_back(b);}}std::vector<int> ans = BFS(1);//outputfor (int i = 0; i < ans.size(); ++i){if(i != ans.size()-1)printf("%d ", ans[i]);else printf("%d\n", ans[i]);}}return 0;}
- 1004. Counting Leaves (30) PAT+BFS
- PAT 1004. Counting Leaves (30)(BFS)
- 1004. Counting Leaves (30)[bfs]
- 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)
- pat 1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- PAT:1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- [PAT]1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- PAT:1004. Counting Leaves (30)
- PAT:1004. Counting Leaves (30)
- Android Notification通知详解
- java API chm html 1.5 1.6 中文版英文版
- Tomcat 7的WebSocket实现(上)
- 2011年蓝桥杯第九题
- CareerCup Binary Tree the Maximum of 人
- 1004. Counting Leaves (30) PAT+BFS
- ios ViewController 页面跳转
- android 使用LocationClient获取精度,纬度坐标
- MapReduce执行过程
- 安卓SDK环境配置
- 期末考试编程题
- struts2随笔(一)Action、struts.xml、Interceptor细节
- 苹果App删除 AppStore应用删除指南
- POJ3228 并查集或二分最大流枚举答案