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
0 1
评价:此题难点应该就是阅读理解吧。
代码
#include<iostream>
#include<cstdio>
#include<map>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
vector<int> graph[105];
int n,m;
int deep=0;
int ans[105];
void dfs(int v,int _deep)
{
if(graph[v].size()==0)
{
ans[_deep]++;
deep=max(deep,_deep);
return;
}
for(int i=0;i<graph[v].size();i++)
dfs(graph[v][i],_deep+1);
}
int main()
{
cin>>n>>m;
int x,num,y;
while(m--)
{
cin>>x>>num;
while(num--)
{
cin>>y;
graph[x].push_back(y);
}
}
//cout<<graph[1].size()<<endl;
dfs(1,0);
for(int i=0;i<deep;i++)
cout<<ans[i]<<" ";
cout<<ans[deep];
return 0;
}

本文介绍了一种算法,用于解决家族树中各层级无子女成员数量的统计问题。输入包括家族树的节点数量及非叶节点详情,通过递归深度优先搜索遍历家族树并统计各层级叶节点数目。
1657

被折叠的 条评论
为什么被折叠?



