1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| #include <bits/stdc++.h> #define int long long #define pb push_back using std::cin, std::cout, std::string; int read(int x = 0, int f = 0, char ch = getchar()) { while (ch < 48 or 57 < ch) f = ch == 45, ch = getchar(); while(48 <= ch and ch <= 57) x = x * 10 + ch - 48, ch = getchar(); return f ? -x : x; } const int N = 1e6 + 5; const int INF = 1 << 30;
int n, a[N], cnt[N], ans; std::vector<int> g[N]; void dfs(int u, int fa) { ans += cnt[a[u]]; int tmp = cnt[a[u]]; for (auto v : g[u]) if (v ^ fa) cnt[a[u]] = 1, dfs(v, u); cnt[a[u]] = tmp + 1; } void solve() { n = read(), ans = 0; for (int i = 1; i <= n; i++) a[i] = read(), g[i].clear(), cnt[i] = 0; for (int i = 1, u, v; i < n; i++) u = read(), v = read(), g[u].pb(v), g[v].pb(u); dfs(1, 0); cout << ans << '\n'; }
signed main() { #ifndef ONLINE_JUDGE freopen("D.in", "r", stdin); #endif for (int T = read(); T--; solve()); return 0; }
|