CF 766E Mahmoud and a xor trip

题目描述

https://codeforces.com/problemset/problem/766/E

Solution

事实上树上路径问题也不一定必须使用点分治或者数据结构解决 典型数据结构学傻了

首先考虑拆位,那么问题就简单多了

我们令 $f[u][0/1]$ 表示以 $u$ 为起点的路径,异或和为 $0/1$

然后就做完了

时间复杂度 $O(n\log a_i)$

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
42
43
44
45
#include <iostream>
#define maxn 100010
#define maxm 2000010
#define ll long long
using namespace std;

int n, a[maxn];

struct Edge {
int to, next;
} e[maxn * 2]; int c1, head[maxn];
inline void add_edge(int u, int v) {
e[c1].to = v; e[c1].next = head[u]; head[u] = c1++;
}

int f[maxn][2]; ll ans;
void dfs(int u, int fa, int o) {
int d = a[u] >> o & 1;
f[u][d] = 1; f[u][d ^ 1] = 0;
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa) continue;
dfs(v, u, o);
for (int k = 0; k < 2; ++k)
ans += (1ll << o) * f[u][k] * f[v][k ^ 1];
for (int k = 0; k < 2; ++k)
f[u][k] += f[v][k ^ d];
}
}

int main() { fill(head, head + maxn, -1);
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i], ans += a[i];
for (int i = 1; i < n; ++i) {
int x, y; cin >> x >> y;
add_edge(x, y); add_edge(y, x);
}
for (int i = 0; i <= 20; ++i)
dfs(1, 0, i);
cout << ans << "\n";
return 0;
}