#include <bits/stdc++.h>
#define sz(x) int(x.size())
#define in(x) freopen(x, "r", stdin)
#define out(x) freopen(x, "w", stdout)
#define N 100500
#define oo ll(1e16)
#define ft first
#define sd second
#define pb push_back
#define ppb pop_back
#define el '\n'
#define elf endl
#define base ll(1e9 + 7)
using namespace std;
typedef long long ll;
typedef long double ld;
ll n, ans, a[N], cnt[N][25][2];
vector <int> g[N];
void dfs(int v, int pr) {
for (int i = 0; i < 23; i++) {
ll x = (a[v] >> i);
cnt[v][i][x & 1]++;
}
ans += a[v];
for (int i = 0; i < sz(g[v]); i++) {
int to = g[v][i];
if (to == pr)
continue;
dfs(to, v);
for (int cr = 0; cr < 23; cr++) {
for (int j = 0; j < 2; j++)
ans += (1ll << cr) * cnt[v][cr][j] * cnt[to][cr][j ^ 1];
ll x = a[v] >> cr;
int nw = x & 1;
for (int j = 0; j < 2; j++)
cnt[v][cr][j] += cnt[to][cr][nw], nw ^= 1;
}
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// in("input.txt");
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n - 1; i++) {
int v, u;
cin >> v >> u;
v--; u--;
g[v].pb(u);
g[u].pb(v);
}
dfs(0, -1);
cout << ans;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
6 ms |
2688 KB |
Output is correct |
2 |
Correct |
6 ms |
2688 KB |
Output is correct |
3 |
Correct |
6 ms |
2816 KB |
Output is correct |
4 |
Correct |
7 ms |
3200 KB |
Output is correct |
5 |
Correct |
7 ms |
3200 KB |
Output is correct |
6 |
Correct |
85 ms |
54136 KB |
Output is correct |
7 |
Correct |
84 ms |
54136 KB |
Output is correct |
8 |
Correct |
86 ms |
47736 KB |
Output is correct |
9 |
Correct |
89 ms |
47096 KB |
Output is correct |
10 |
Correct |
117 ms |
46460 KB |
Output is correct |