PAT_1004: Counting Leaves

来源:互联网 发布:centos6网络配置 编辑:程序博客网 时间:2024/06/05 05:18
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 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 Input
2 1
01 1 02
Sample Output


备注:宽度优先搜索(breadth-first search), 用队列实现。


#include<iostream>#include<queue>using namespace std;#define MAXNODES 101#define ISLEAF -1struct node{int k;int c[100];};int main(){int n,m,id,k;int i,j;int curlev_size;struct node tree[MAXNODES];cin>>n>>m;/*只有一个root节点的情况*/if(n==1){cout<<1;return 0;}for(i = 0;i < MAXNODES; i++)tree[i].k = ISLEAF; /*初始化*/for(i = 0; i < m; i++){cin>>id>>k;tree[id].k = k;for (j = 0; j < k; j++)cin>>tree[id].c[j]; }/*breath-firth search*/queue<struct node> q;q.push(tree[1]);while(!q.empty()){curlev_size = q.size();int count_leaf = 0;while(curlev_size>0){struct node p = q.front();q.pop();if(p.k==ISLEAF)count_leaf++;else{for(i=0;i<p.k;i++)q.push(tree[p.c[i]]);}curlev_size--;}if(q.size()==0)cout<<count_leaf;elsecout<<count_leaf<<" ";}return 0;}

原创粉丝点击