#include<bits/stdc++.h> usingnamespacestd; constint N = 1e6 + 5; vector<int> g[N]; int t, n; longlong res, dp1[N], dp2[N];
voiddfs(int u, int fa){ dp1[u] = 1; for (auto v : g[u]) { if (v == fa) continue; dfs(v, u); dp2[u] = max(dp2[u], dp2[v]); dp1[u] += dp1[v]; } dp2[u] += n - dp1[u]; }
intmain(){ scanf("%d", &t); while (t--) { scanf("%d", &n); res = 0; for (int i = 0; i <= n; i++) { g[i].clear(); dp1[i] = 0; dp2[i] = 0; } for (int i = 2; i <= n; i++) { int x; scanf("%d", &x); g[x].push_back(i); } dfs(1, -1); for (int i = 1; i <= n; i++) res += dp1[i]; printf("%lld\n", res + dp2[1]); } return0; }