PAT (Advanced Level) 1004. Counting Leaves (30)
简单DFS。
#include<iostream> #include<cstring> #include<cmath> #include<algorithm> #include<cstdio> #include<vector> using namespace std; const int maxn=100+10; vector<int>g[maxn]; int n,m; int ans[maxn]; int root; int Deep; void dfs(int x,int deep) { Deep=max(Deep,deep); if(g[x].size()==0) { ans[deep]++; return ; } for(int i=0;i<g[x].size();i++) dfs(g[x][i],deep+1); } int main() { scanf("%d%d",&n,&m); for(int i=0;i<=n;i++) g[i].clear(); for(int i=1;i<=m;i++) { int id; scanf("%d",&id); int k; scanf("%d",&k); while(k--) { int id2; scanf("%d",&id2); g[id].push_back(id2); } } memset(ans,0,sizeof ans); root=1; Deep=1; dfs(root,1); for(int i=1;i<=Deep;i++) { printf("%d",ans[i]); if(i<Deep) printf(" "); else printf("\n"); } return 0; }