老样子,附上题目的链接和内容:
https://pintia.cn/problem-sets/994805342720868352/problems/994805521431773184
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
这道题的意思就是让我们去统计书上有几个没有孩子的节点,也就是叶子节点,然后输入的格式是节点数,有孩子的节点数
有孩子的节点id,有几个孩子,孩子的ID叫什么
然后按层序输出每层的孩子节点
然后这道题目的话,我选择使用DFS去递归,因为递归如果第一个节点一直有,他会一直进行下去,所以DFS可以一开始就进行很大深度的搜索,然后每次找父节点的子节点,每个子节点都递归,如果这个子节点有孩子,那么就继续递归,然后用一个变量来更新当前找到的最大深度。每次递归一次,如果找到了叶子节点,就保存在数组中。
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> level(201,0);
vector<vector<int> > tree(101); //这里准确来说应该是100,但是为了避免越界我们还是开的小一点
int max_d=-1;
void DFS(int d,int fid)
{
max_d=max(d,max_d);//不断更新最大的根
if(tree[fid].empty())//如果当前没有子节点
level[d]++;//在该层上的叶子数增加1
for(vector<int>::iterator iter=tree[fid].begin();iter!=tree[fid].end();iter++)//这里用了迭代器来进行vector的遍历操作
DFS(d+1,*iter);//对更深一层来进行搜索
}
int main()
{
int m,n;
cin>>m>>n;
for(int i=0;i<n;i++)
{
int fid,num,cid;
cin>>fid;
cin>>num;
for(int j=0;j<num;j++)
{
cin>>cid;
tree[fid].push_back(cid);//vector的特定功能,把一个数据放在后面
}
}
DFS(0,1);//进行递归
for(int i=0;i<=max_d;i++)//从0开始到最大的根开始打印
{
if(i!=0)
cout<<" ";
cout<<level[i];
}
return 0;
}
注意点1
for(vector<int>::iterator iter=tree[fid].begin();iter!=tree[fid].end();iter++)//这里用了迭代器来进行vector的遍历操作
DFS(d+1,*iter);//对更深一层来进行搜索
这里iter的格式是vector<int>iterator,这个格式跟模板的调用很相似,然后vector有begin()和end()和empty()来查找第一和最后的元素
push_back可以在后面增加一个元素
然后iter是一个指针,所以要取值必须要加*