题意:
给一棵树,每个点有点权。
询问任意两点路径上点权的异或和。
做法:
由于是异或和,可以先枚举每一位,分别DP。
记f[u][0/1]为以u为根的子树中,路径异或值为0/1的点对数量。
ans统计时利用乘法原理。然后要再乘上
2p
(p是当前的位数)。
推f[]的时候按照当前位的0/1分类讨论一下。
代码:
/*************************************************************
Problem: codeforces 766E - Mahmoud and a xor trip
User: bestFy
Language: C++
Result: Accepted
Time: 187 ms
Memory: 8600 KB
Submit_Time: 2018-01-03 15:32:23
*************************************************************/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cctype>
using namespace std;
typedef long long LL;
inline LL read()
{
char ch = getchar(); LL x = 0; int op = 1;
for(; !isdigit(ch); ch = getchar()) if(ch == '-') op = -1;
for(; isdigit(ch); ch = getchar()) x = x*10 + ch-'0';
return x*op;
}
const int N = 100010;
int n, cnt;
LL ans, f[N][2];
int head[N], a[N];
struct Edge{
int to, nex;
Edge() {}
Edge(int x, int y) { to = x, nex = y; }
}e[N<<1];
inline void addEdge(int x, int y){ e[++ cnt] = Edge(y, head[x]); head[x] = cnt; }
inline void dfs(int u, int lst, int p)
{
int x = a[u]>>p&1; f[u][x] = 1; f[u][x^1] = 0;
for(int i = head[u]; i; i = e[i].nex) {
int v = e[i].to; if(v == lst) continue;
dfs(v, u, p); ans += (f[u][0]*f[v][1] + f[u][1]*f[v][0])*(1<<p);
if(!x) f[u][0] += f[v][0], f[u][1] += f[v][1];
else f[u][0] += f[v][1], f[u][1] += f[v][0];
}
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i ++) ans += (a[i] = read());
for(int i = 1; i < n; i ++) {
int x = read(), y = read();
addEdge(x, y); addEdge(y, x);
}
for(int i = 0; i <= 20; i ++) dfs(1, 0, i);
cout << ans;
return 0;
}