Codeforces766E Mahmoud and a xor trip(按位+树形DP)

题意

树有 N(1n105) 个节点,每个点有点权 ai(0ai106) ,求 。两点间距离:两点间所有点权的异或值。


分析

往往涉及到异或的题都要用二进制来快速处理。因为 0ai106 ,所以枚举 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值