Untitled

mail@pastecode.io avatar
unknown
c_cpp
a year ago
2.0 kB
2
Indexable
Never
#include "bits/stdc++.h"
using namespace std;

#ifdef LOCAL
#include "debug.h"
#else
#define debug(x...)
#endif

#define int long long

constexpr int maxN = 2e5;

int n;
vector<int> a(maxN);
vector<int> graph[maxN];
vector<long long> dp(maxN, 0);
vector<int> ch(maxN, 0);
vector<long long> ans(maxN, -1);

void clean(int k) {
    for (int i = 0; i < k; i++) {
        dp[i] = 0;
        ch[i] = 0;
        ans[i] = -1;
        graph[i].clear();
    }
}

void dfs1(int u, int p) {
    for (int &g : graph[u]) {
        if (g != p) {
            dfs1(g, u);
            ch[u] += ch[g] + 1;
            dp[u] += dp[g];
            dp[u] += 1LL * (ch[g] + 1) * (a[g] ^ a[u]);
        }
    }
}

void dfs2(int u, int from) {
    long long oldf = dp[from];
    dp[from] = dp[from] - dp[u] - (ch[u] + 1) * (a[u] ^ a[from]);
    long long oldchf = ch[from];
    ch[from] = ch[from] - ch[u] - 1;
    long long oldchu = ch[u];
    ch[u] = n - 1;
    long long rec = 0;
    for (int &g : graph[u]) {
        rec += dp[g] + (ch[g] + 1) * (a[g] ^ a[u]);
    }
    long long oldu = dp[u];
    dp[u] = rec;
    ans[u] = dp[u];
    for (int &g : graph[u]) {
        if (ans[g] == -1) {
            dfs2(g, u);
        }
    }
    dp[from] = oldf;
    dp[u] = oldu;
    ch[from] = oldchf;
    ch[u] = oldchu;
}

void solve() {
    cin >> n;
    clean(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    for (int i = 0; i < n - 1; i++) {
        int u, v;
        cin >> u >> v;
        u--; v--;
        graph[u].push_back(v);
        graph[v].push_back(u);
    }
    dfs1(0, -1);
    ans[0] = dp[0];
    for (int &g : graph[0]) {
        dfs2(g, 0);
    }
    for (int i = 0; i < n; i++) {
        cout << ans[i] << ' ';
        assert(ans[i] != -1);
    }
    cout << '\n';
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int tests = 1;
    cin >> tests;
    while (tests--) {
        solve();
    }
    return 0;
}