【PAT】1004. Counting Leaves (30)

来源:互联网 发布:乡村旅游源码下载 编辑:程序博客网 时间:2024/05/14 15:52
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

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 Input
2 101 1 02
Sample 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;}



0 0
原创粉丝点击