Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define _test int _TEST; cin>>_TEST; while(_TEST--)
- #define pb push_back
- int main()
- {
- _test
- {
- int n;
- cin>>n;
- vector<vector<int>> tree(n);
- for(int i=1; i<n; i++)
- {
- int p;
- cin>>p;
- tree[p-1].pb(i);
- }
- vector<int> subtree(n);
- function<void(int)> DFS = [&](int u)
- {
- subtree[u]++;
- for(auto v: tree[u])
- {
- DFS(v);
- subtree[u] += subtree[v];
- }
- };
- DFS(0);
- int ans = 0;
- function<void(int, int)> DFS2 = [&](int u, int x)
- {
- ans += (x > 0);
- if(x > 0) x--;
- int tot = 0;
- for(auto v: tree[u])
- tot += subtree[v];
- for(auto v: tree[u])
- DFS2(v, x+tot-subtree[v]);
- };
- DFS2(0, 0);
- cout<<ans/2<<"\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment