We'd like to thank you all for participating in the contest, and hope you enjoyed it. Hope to see you again soon!
Author: vrintle
As we have $$$t_i$$$'s only till $$$n \leq 2 \cdot 10^5$$$, therefore we can easily say that the bit count can be upto $$$\log(n) = 18$$$. Let's iterate over every bit count and maximize our answer for each group of nodes.
Let's consider current bit count to be $$$x$$$, so let's mark nodes with bit count $$$x$$$ in red color, and the other nodes in black color. So, this problem boils down to finding maximum distance between any two red colored nodes (a similar codeforces problem). The answer to this sub problem is the diameter of this red-black tree. Note that, in this version, the diameter ends will always be red nodes.
Time complexity: $$$\mathcal{O}(n \cdot \log{n})$$$
PS: I have thought about this partial diameter problem before the actual div3 contest linked above.
#include <bits/stdc++.h>
using namespace std;
#define int int64_t
#define endl '\n'
#define sz(v) ((int) v.size())
#define all(v) v.begin(), v.end()
#define vi vector<int>
#define pii pair<int, int>
#define inf 2e18
int max(int x, int y) { return x > y ? x : y; }
int min(int x, int y) { return x < y ? x : y; }
const int N = 2e5 + 7;
vi g[N];
void solve() {
int n;
cin >> n;
vi a(n);
for(int i = 0; i < n; i++) {
cin >> a[i];
a[i] = __builtin_popcount(a[i]);
g[i].clear();
}
for(int _ = 0; _ < n - 1; _++) {
int u, v;
cin >> u >> v;
u--; v--;
g[u].push_back(v);
g[v].push_back(u);
}
int ans = 0;
for(int b = 1; b <= 20; b++) {
vi dist(n, inf);
function<void(int, int)> dfs = [&](int u, int p) {
for(auto& v: g[u]) {
if(v == p) continue;
dist[v] = dist[u] + 1;
dfs(v, u);
}
};
for(int i = 0; i < n; i++) {
if(a[i] == b) {
dist[i] = 0;
dfs(i, -1);
break;
}
}
int mx = 0;
for(int i = 0; i < n; i++) {
if(a[i] == b) mx = max(mx, dist[i]);
}
for(int i = 0; i < n; i++) {
if(a[i] == b && dist[i] == mx) {
dist.assign(n, inf);
dist[i] = 0;
dfs(i, -1);
break;
}
}
for(int i = 0; i < n; i++) {
if(a[i] == b) ans = max(ans, dist[i]);
}
}
cout << ans;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifdef VRINTLE
freopen("./tests/tree_27.txt", "r", stdin);
freopen("./out.txt", "w", stdout);
freopen("./err.txt", "w", stderr);
#endif
int t = 1;
cin >> t;
while(t--) {
solve();
cout << endl;
}
return 0;
}



