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 Input2 1 01 1 02Sample Output
0 1题意:给定一棵树,求每一层叶子数
输入:
第一行输入节点数n,第二行输入非叶子节点数m
接下来m行,输入一个非叶子节点的id,再输入孩子数k,接着输入k个孩子的id。
输出:
在一行上输出每一层叶子数,用空格隔开,最后不能有空格。
思路:
这个题我用一个关联容器来表达一棵树定义map<string,vector<string>> Tree,关键字表示节点的编号,关键字对应的值表示节点的孩子。例如<"01",{"02,"03}>表示节点“01”的孩子是02,03,然后用DFS遍历这棵树,遇到vector容器为空的即为叶节点,对应的层叶节点加一
#include<iostream>
#include<map>
#include<vector>
using namespace std;
map<string,vector<string>> Tree;
int leaves[101];//leaves[i]表示第i层叶子数
void DFS(string start,int level)
{
if(Tree[start].empty())
{
++leaves[level];
return;
}
vector<string>::iterator i;
for(i=Tree[start].begin();i!=Tree[start].end();i++)
DFS(*i,level+1) ;
}
int main()
{
int n,m,k,numleaf=0;
string id,childid;
cin>>n>>m;
for(int i=0;i<m;i++)
{
cin>>id>>k;
while(k--)
{
cin>>childid;
Tree[id].push_back(childid);
}
}
DFS("01",0);
cout<<leaves[0];
numleaf+=leaves[0];
for(int i=1;numleaf<n-m;i++)
{
cout<<" "<<leaves[i];
numleaf+=leaves[i];
}
cout<<endl;
return 0;
}