1004 Counting Leaves
解题思路:利用深度优先搜索,遍历树
#include<iostream> #include<vector> using namespace std; int n,m,maxlevel,numEachleval[100]={0}; vector<int>child[100]; void dfs(int curid,int curlevel){ if(curlevel>maxlevel)maxlevel=curlevel; if(child[curid].size()>0){ for(auto x:child[curid]){ dfs(x,curlevel+1); } } else{ numEachleval[curlevel]++; } } int main(){ cin>>n>>m; for(int i=0;i<m;i++){ int id,j,k; cin>>id>>k; while(k--){ cin>>j; child[id].emplace_back(j); } } dfs(1,1); for(int i=1;i<=maxlevel;i++){ if(i>1)cout<<' '; cout<<numEachleval[i]; } }
标签:PAT,int,dfs,curid,curlevel,第二天,child,maxlevel From: https://www.cnblogs.com/jerry-autumn/p/17056692.html