codeforces766E - Mahmoud and a xor trip

20 篇文章 0 订阅
20 篇文章 0 订阅

题面在这里

题意:

给一棵树,每个点有点权。
询问任意两点路径上点权的异或和。

做法:

由于是异或和,可以先枚举每一位,分别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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值