Ankit_132

F

Dec 19th, 2023
606
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1.  
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. #define _test   int _TEST; cin>>_TEST; while(_TEST--)
  6. #define pb     push_back
  7.  
  8. int main()
  9. {
  10.     _test
  11.     {
  12.         int n;
  13.         cin>>n;
  14.  
  15.         vector<vector<int>> tree(n);
  16.  
  17.         for(int i=1; i<n; i++)
  18.         {
  19.             int p;
  20.             cin>>p;
  21.  
  22.             tree[p-1].pb(i);
  23.         }
  24.  
  25.         vector<int> subtree(n);
  26.  
  27.         function<void(int)> DFS = [&](int u)
  28.         {
  29.             subtree[u]++;
  30.  
  31.             for(auto v: tree[u])
  32.             {
  33.                 DFS(v);
  34.                 subtree[u] += subtree[v];
  35.             }
  36.         };
  37.  
  38.         DFS(0);
  39.  
  40.         int ans = 0;
  41.  
  42.         function<void(int, int)> DFS2 = [&](int u, int x)
  43.         {
  44.             ans += (x > 0);
  45.  
  46.             if(x > 0)       x--;
  47.  
  48.             int tot = 0;
  49.             for(auto v: tree[u])
  50.                 tot += subtree[v];
  51.  
  52.             for(auto v: tree[u])
  53.                 DFS2(v, x+tot-subtree[v]);
  54.         };
  55.  
  56.         DFS2(0, 0);
  57.  
  58.         cout<<ans/2<<"\n";
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment