1004 Counting Leaves (30 分)
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
Input Specification:
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
.
The input ends with N being 0. That case must NOT be processed.
Output Specification:
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 is0
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:
0 1
思路:
利用BFS从上往下一层一层的找
我们就可以把信息存到一个链表数组中也就是邻接表
然后不断的入队
用一个变量记数叶子节点
再用一个记录当前这一层的结点是否全部判断完毕
#include<cstdio>
#include<cstdlib>
#include<list>
#include<queue>
using namespace std;
void countingLeaves(list<int> *ln)
{
int levelCount,leavesCount,levelTemp;
queue<list<int>> q;
leavesCount = 0;//叶子节点个数
levelCount = 0;//每一层节点的个数
levelTemp = 0;//用来判别当前层是否全部判断完毕
//第一层特殊处理
printf("0");
for(list<int>::iterator it = ln[1].begin();it != ln[1].end();it++){
q.push(ln[*it]);
}
levelCount = q.size();
while(!q.empty()){
list<int> tln = q.front();
levelTemp++;//处理一个就累加一个
q.pop();
//必须是先把孩子入队
for(list<int>::iterator it = tln.begin();it != tln.end();it++){
q.push(ln[*it]);
}
//当为叶子时累加一
if(tln.size() == 0){
leavesCount++;
}
//核心:
//当该层处理完之后需更新下一层的个数
//而下一层的个数恰好是队列的个数
//接着其他变量挨着更新并打印
if(levelTemp == levelCount){
levelCount = q.size();
levelTemp = 0;
printf(" %d",leavesCount);
leavesCount = 0;
}
}
}
int main()
{
//初始化
int N,M;
int nonleavesId,k,childId;
scanf("%d%d",&N,&M);
list<int> ln[101];
//处理只有根结点01的情况
if(N == 1){
scanf("%d%d",&nonleavesId,&k);
printf("1");
return 0;
}
for(int i = 0;i < M;i++){
scanf("%d%d",&nonleavesId,&k);
for(int j = 0;j < k;j++){
scanf("%d",&childId);
ln[nonleavesId].push_back(childId);
}
}
//计算
countingLeaves(ln);
return 0;
}