PAT A 1004. Counting Leaves (30)【vector+dfs】

题目链接:https://www.patest.cn/contests/pat-a-practise/1004

大意:输出按层次输出每层无孩子结点的个数

思路:vector存储结点,dfs遍历

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<string>
 4 #include<vector>
 5 #include<algorithm>
 6 using namespace std;
 7 const int maxn=1e2+10;
 8 int n,m,k,x,f[maxn],deep,y;
 9 vector<int> t[maxn];
10 void init()
11 {
12     cin>>n>>m;
13     while(m--)
14     {
15         cin>>x>>k;
16         while(k--)
17         {
18             cin>>y;
19             t[x].push_back(y);
20         }
21     }
22 }
23 void dfs(int x,int dep)
24 {
25    deep=max(dep,deep);
26    if(t[x].size()==0)f[dep]++;
27    for(int i=0;i<t[x].size();i++)
28         dfs(t[x][i],dep+1);
29 }
30 
31 int main()
32 {
33   init();
34   dfs(1,0);
35   for(int i=0;i<=deep;i++)
36     printf("%s%d",i?" ":"",f[i]);
37   printf("
");
38  return 0;
39 }
原文地址:https://www.cnblogs.com/demian/p/6062864.html