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 output 0 1
in a line.
Sample Input:
2 1
01 1 02
Sample Output:
0 1
利用DFS求得树中每一层的叶节点数目存储在hashtable中,注意用maxh保存树的最大深度。注意此题宜用DFS(1,1)进入递归求解。
参考代码:
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn=110;
vector<int>child[maxn];
int n,m;
int maxh=1;
int hashtable[maxn]={0}; //用来存放每一层叶结点数
void DFS(int index,int depth)
{
maxh=max(depth,maxh);
if(child[index].size()==0) //叶结点
{
hashtable[depth]++;//对应层上叶结点数+1
return;//返回。非常重要!
}
for(int i=0;i<child[index].size();++i)
DFS(child[index][i],depth+1);
}
int main()
{
scanf("%d%d",&n,&m);//题目有问题,说是n为0是输入结束,但其实是这种形式
int id,k,son;
for(int i=0;i<m;++i)
{
scanf("%d%d",&id,&k);
for(int j=0;j<k;++j)
{
scanf("%d",&son);
child[id].push_back(son);
}
}
DFS(1,1);
for(int i=1;i<=maxh;++i)
{
printf("%d",hashtable[i]);
if(i<maxh)
printf(" ");
}
printf("\n");
return 0;
}
BFS参考代码:
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
const int N=105;
vector<int> child[N];
int h[N]={0};//给结点所处的层号,从1开始
int leaf[N]={0};// 存放每层叶子结点数
int maxh=0; //树的最大深度
void BFS()
{
queue<int> q;
q.push(1);//将根结点压入队列
while(!q.empty())
{
int id=q.front();
q.pop();
maxh=max(maxh,h[id]);//更新最大深度
if(child[id].size()==0) //叶结点
{
leaf[h[id]]++;
}
for(int i=0;i<child[id].size();++i)
{
h[child[id][i]]=h[id]+1;//子结点编号为child[id][i]
q.push(child[id][i]); //将子结点入队
}
}
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=0;i<m;++i)
{
int parent,k,son;
scanf("%d%d",&parent,&k);
for(int j=0;j<k;++j)
{
scanf("%d",&son);
child[parent].push_back(son);
}
}
h[1]=1; //初始化根节点
BFS();
for(int i=1;i<=maxh;++i)
{
if(i==1)
printf("%d",leaf[i]);
else
printf(" %d",leaf[i]);
}
return 0;
}