http://acm.hust.edu.cn/thx/problem.php?id=1422 STL+DFS #include<iostream> #include<cstdio> #include<string.h> #include<vector> #include<map> #include<cmath> #include<stack> #include<queue> #include<algorithm> using namespace std; #define inf 0x7fffffff vector<int> v[50005]; int a[50005]; int dfs(int x) { int i,j; a[x]+=v[x].size(); for(i=0;i<v[x].size();i++) { j=v[x][i]; a[x]+=dfs(j); } return a[x]; } int main() { //freopen("a.txt","r",stdin); int t; scanf("%d",&t); for(int ca=1;ca<=t;ca++) { int n,m; scanf("%d",&n); int i,j,k; //memset(a,0,sizeof(a)); for(i=0;i<=n;i++) v[i].clear(),a[i]=0; for(i=1;i<n;i++) { int num; scanf("%d",&num); v[num-1].push_back(i); } dfs(0); printf("Case #%d: ",ca); printf("%d",a[0]); for(i=1;i<n;i++) printf(" %d",a[i]); printf("/n"); } return 0; }