fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5. const int MAXN = 300000;
  6.  
  7. vector<int> adj[MAXN+1];
  8. vector<int> depths[MAXN+1];
  9. int maxd;
  10.  
  11. void dfs(int u, int p, int d) {
  12. // record node u at depth d
  13. depths[d].push_back(u);
  14. maxd = max(maxd, d);
  15. // recurse on children
  16. for (int v : adj[u]) {
  17. if (v == p) continue;
  18. dfs(v, u, d+1);
  19. }
  20. }
  21.  
  22.  
  23. int main(){
  24. ios::sync_with_stdio(false);
  25. cin.tie(nullptr);
  26.  
  27. int T;
  28. cin >> T;
  29. while (T--) {
  30. int n;
  31. cin >> n;
  32. // clear adjacency & depths
  33. for (int i = 1; i <= n; i++) {
  34. adj[i].clear();
  35. depths[i].clear();
  36. }
  37. maxd = 0;
  38.  
  39. // read the tree
  40. for (int i = 2 ; i <= n; i++) {
  41. int p ; cin >> p ;
  42. adj[p].push_back(i);
  43. }
  44.  
  45. // bucket nodes by depth starting from node 1
  46. dfs(1, 0, 0);
  47.  
  48. // dp[d] = number of ways to choose one node in each depth ≤ d
  49. vector<ll> dp(maxd+1);
  50. dp[0] = 1;
  51. for (int d = 1; d <= maxd; d++) {
  52. ll cnt = depths[d].size();
  53. dp[d] = cnt * dp[d-1];
  54. }
  55.  
  56. ll res = 0;
  57. for (int d = 0; d <= maxd; d++) {
  58. res += dp[d];
  59. }
  60. // does thsi realyl wewor kw
  61. cout << res << "\n";
  62. }
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0.01s 17748KB
stdin
3
4
1 2 1
3
1 2
7
1 2 2 1 4 5
stdout
5
3
15