【PAT】1004. Counting Leaves (30)
来源:互联网 发布:乡村旅游源码下载 编辑:程序博客网 时间:2024/05/14 15:52
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 childfor 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
分析:
(1)建树(2)统计每一层中没有子节点的节点数
运用队列来实现BFS,关键是遍历完一层后要进行一次输出,所以要标记层数。
参考代码如下:
#include<iostream>#include<vector>#include<queue>using namespace std;vector< vector<int> > relation;vector<int> BFS(int s){int level = 0, cur_level = 0;vector<int> ans;queue< pair<int,int> > que;que.push(make_pair(s,0)); // s 代表根节点,0代表目前在第0层int num_nochild = 0; //统计该层没有子节点的节点数while(!que.empty()){level = que.front().second;if(cur_level < level){ans.push_back(num_nochild);num_nochild = 0;cur_level = level;}int index = que.front().first;if(relation[index].size() == 0) num_nochild ++;for(int i=0; i<relation[index].size(); i++){ que.push(make_pair(relation[index][i],cur_level + 1) );}que.pop();}ans.push_back(num_nochild);return ans;}int main(){int N,M;cin>>N>>M;relation.resize(N+1); int a,k,i,j,temp;for(j=0; j<M; j++){cin>>a>>k;for(i=0; i<k; i++){cin>>temp;relation[a].push_back(temp); }}vector<int> result = BFS(1);for(i=0; i<result.size(); i++){if(i != result.size() - 1){cout<<result[i]<<" ";}elsecout<<result[i]<<endl;}return 0;}
- 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)
- 【PAT】1004. Counting Leaves (30)
- pat 1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- 我和权威的故事
- CentOS系统文件名中不同的颜色都代表什么意思
- 2014-year☞fisrt☞spring☞PropertyPlaceholderConfigurer
- poj1947之删除最少边保留m个节点
- STL中map用法详解
- 【PAT】1004. Counting Leaves (30)
- hid例程
- MySQL为什么要set names
- eclipse下实现maven项目在tomcat容器热部署方法
- 博主前来报道
- my js library
- 为不同种类的文档建立文档模板
- IOS应用如何配置iTunes文件共享
- Struts2 基础