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 is 0
leaf node; and on the next level, there is 1
leaf node. Then we should output0 1
in a line.
Sample Input:
2 1
01 1 02
Sample Output:
0 1
作者: CHEN, Yue
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
代码长度限制: 16 KB
题目大意:给出一个家谱树,要你找出每一代没有当父母的人,其实就是像题目的名字那样,数叶子。
解题思路:层序遍历整棵树,更改每个结点的level,然后对每一个叶节点,把相应的res[level]++,最后依次输出。
AC代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>
using namespace std;
int n,m;
int maxlevel=0;
const int maxn=1000;
int ans[maxn]={0};
struct node{
int level;
vector<int> child;
}ped[maxn];
void levelorder(int root);
int main()
{
int nodes=0;
cin>>n>>m;
int k,child,father;
for(int i=0;i<m;i++)//建树
{
cin>>father>>k;
for(int j=0;j<k;j++)
{
cin>>child;
ped[father].child.push_back(child);
nodes++;
}
}
levelorder(1);
//cout<<"maxlevel is "<<maxlevel<<endl;
for(int i=1;i<=maxlevel;i++)
{
cout<<ans[i];
if(i<maxlevel)
cout<<" ";
}
return 0;
}
void levelorder(int root)
{
queue<int> q;
q.push(root);
ped[root].level=1;
int level=ped[root].level;
while(!q.empty())
{
int top=q.front();
q.pop();
level=ped[top].level;
//printf("now the node is %d and the level is %d\n",top,level);
if(ped[top].child.size()==0)//叶子结点
{
ans[level]++;
if(level>maxlevel)
maxlevel=level;//记录最大深度
}//遍历每一个结点,如果是叶节点,就把该层的叶节点数+1
for(int i=0;i<ped[top].child.size();i++)
{
int child=ped[top].child[i];
ped[child].level=ped[top].level+1;
q.push(child);
}
}
}