题意
树有 N(1 ≤ n ≤ 105) 个节点,每个点有点权 ai(0 ≤ ai ≤ 106) ,求 ∑两点间距离 。两点间距离:两点间所有点权的异或值。
分析
往往涉及到异或的题都要用二进制来快速处理。因为 0 ≤ ai ≤ 106 ,所以枚举 20 位。
按位处理,记录当前节点到它以下的每个节点的距离在当前位的异或值为 1 或
0 的路径数量(也可说点对)。
num[u][0] 记录到 u 节点时异或值为0 的路径数量
num[u][1] 记录到 u 节点时异或值为1 的路径数量
代码
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<cctype>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<iomanip>
#include<sstream>
#include<limits>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const ll INF = 1e18;
const int maxn = 2e5+10;
const ll MOD = 1000000007;
const double EPS = 1e-10;
const double Pi = acos(-1.0);
int a[maxn];
int num[maxn][2];
ll ans;
vector<int> G[maxn];
void dfs(int now,int fa,int pos)
{
int t = (a[now]>>pos) & 1;
num[now][t] = 1; num[now][t^1] = 0;
ll res = 0;
for(int i = 0; i < G[now].size();i++)
{
int nxt = G[now][i];
if (nxt == fa) continue;
dfs(nxt,now,pos);
res += num[now][1]*num[nxt][0]+num[now][0]*num[nxt][1];
num[now][t^1] += num[nxt][1];
num[now][t^0] += num[nxt][0];
}
ans += res<<pos;
}
int main(){
#ifdef LOCAL
//freopen("C:\\Users\\lanjiaming\\Desktop\\acm\\in.txt","r",stdin);
//freopen("output.txt","w",stdout);
#endif
//ios_base::sync_with_stdio(0);
int n;
cin>>n;
ans = 0;
for(int i = 1; i <= n; i++)
{
cin>>a[i];
ans += a[i];
G[i].clear();
}
for(int i = 0; i < n-1; i++)
{
int u,v;
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
for(int i = 0; i <= 20; i++)
dfs(1,0,i);
cout<<ans<<endl;
return 0;
}