int n, m, k, q; map<int, int> mp[N]; vector<int> son[N]; int col[N]; ll ans = 0; voiddfs(int x, int f) { mp[x][col[x]]++; for (auto y : son[x]) { if (y == f) continue; dfs(y, x); if (mp[y].contains(col[x])) { ans += mp[y][col[x]]; mp[y].erase(col[x]); } if (mp[y].size() > mp[x].size()) swap(mp[x], mp[y]); for (auto [key, val] : mp[y]) { if (mp[x].contains(key)) ans += 1LL * val * mp[x][key]; mp[x][key] += val; } } } voidwork() { cin >> n; // clear for (int i = 1; i <= n; i++) { mp[i].clear(); son[i].clear(); } ans = 0; for (int i = 1; i <= n; i++) cin >> col[i]; for (int i = 1; i < n; i++) { int x, y; cin >> x >> y; son[x].emplace_back(y); son[y].emplace_back(x); } dfs(1, 0); cout << ans << endl; } intmain() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t --> 0) { work(); } }