Mahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by n - 1 undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number ai attached to it.
We define the distance from city x to city y as the xor of numbers attached to the cities on the path from x to y (including both x and y). In other words if values attached to the cities on the path from x to y form an array p of length l then the distance between them is , where is bitwise xor operation.
Mahmoud and Ehab want to choose two cities and make a journey from one to another. The index of the start city is always less than or equal to the index of the finish city (they may start and finish in the same city and in this case the distance equals the number attached to that city). They can't determine the two cities so they try every city as a start and every city with greater index as a finish. They want to know the total distance between all pairs of cities.
The first line contains integer n (1 ≤ n ≤ 105) — the number of cities in Mahmoud and Ehab's country.
Then the second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106) which represent the numbers attached to the cities. Integer ai is attached to the city i.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting that there is an undirected road between cities u and v. It's guaranteed that you can reach any city from any other using these roads.
Output one number denoting the total distance between all pairs of cities.
3 1 2 3 1 2 2 3
10
5 1 2 3 4 5 1 2 2 3 3 4 3 5
52
5 10 9 8 7 6 1 2 2 3 3 4 3 5
131
题意:n个点构成的树,每个点带有一个权,n-1条边,边上权重是边两点的异或运算。由于为树,所以任意两点间可达,求所有点对间的距离和mod 1e9+7
思路:由异或运算想到二进制,可对二进制拆位,分别计算每一位上的贡献最后累加。数据范围是2^20,所以从0到20位,分别计算每一位的贡献。对于每一位计算,考虑到每一个点都是由其叶子节点的信息确定的路径长度,用dfs寻找点对之间的关系。
用cnt[i][0]表示i节点所连接的通路异或结果在该位上是0的数量,cnt[i][1]表示异或结果是1的数量。
则节点u的临界点v,传递的信息权重为 cnt[u][0]*cnt[v][1]+cnt[u][1]*cnt[u][0];
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
int n;
int a[100007];
vector<int> G[100007];
int b[100007]; //存储当前位的,i结点的是否为1
int cnt[100007][2];
long long sum;//储存结果
void dfs(int u, int off) //off表示上一节点
{
cnt[u][0] = cnt[u][1] = 0;
cnt[u][b[u]]++;
//计算to itself
sum += b[u];
for(int i = 0; i < G[u].size(); ++i)
{
int v = G[u][i];
if( v == off) continue;
dfs(v, u);
sum+=cnt[u][0]*cnt[v][1]+cnt[u][1]*cnt[v][0];
//更新结点信息
cnt[u][b[u]^0]+=cnt[v][0];
cnt[u][b[u]^1]+=cnt[v][1];
}
}
int main()
{
cin>>n;
for(int i=1; i<=n; i++)
cin >> a[i];
for(int i=1; i<n; i++)
{
int u,v;
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
long long ans=0;
for(int i=0;i<=20;i++)
{
for(int j=1;j<=n;j++)
if(a[j]&(1<<i))
b[j]=1;
else b[j]=0;
sum=0;
dfs(1,-1);
ans+=(sum<<i);
}
cout << ans;
return 0;
}