跳到正文

题解

题解:P14664 [KenOI 2025] 异或题

CXPapy约 2 分钟
原文

这是 2025年12月8日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年12月8日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟
题目
P14664

版本

  1. v3当前
  2. v2
  3. v1

按位贪心。

分类讨论异或位置为0和1的情况。如果xor为1说明一个为1一个为0,无论怎么分配和都是一样的。如果xor为0那么两个位置相同,那肯定优先选择两者都为1。

但是题目要求 a,b≤na, b \le n 。考虑构造最优解。只需要把 highbit(n)highbit(n) 给 aa,highbit(n−a)highbit(n-a) 给 bb,剩余 n−highbit(n)n-highbit(n) 的xor为0的位置就可以贪心的取1了。

然后题解一堆 O(Tlogn)O(Tlogn)做法。显然可以继续优化。

求 ∑\sum xor为0 的贡献其实就是把0位求出来然后按位取反再乘2。设 fullbase(n)fullbase(n) 为 nn 最高位后全为1的值。那么 fullbase(n−highbit(n))−(n−highbit(n))fullbase(n-highbit(n)) - (n-highbit(n)) 就是0位取反。

xor为1的贡献就是 n−highbit(n)n-highbit(n)。没什么好说的。

求 fullbasefullbase 和求 highbithighbit 方式一致。复杂度为O(Tloglogn)O(Tloglogn)。

代码巨短。输入到输出就两行。

AC Code
C++
#include <iostream>
using namespace std;
typedef long long ll;
int T; ll N;

ll fullbit(ll x){
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    return x;
}

ll highbit(ll x){
    ll res = fullbit(x);
    return res - (res >> 1);
}

int main(){
    ios::sync_with_stdio(false);
    cin >> T;
    while (T--){
        cin >> N;
        ll res = N; N -= highbit(N);
        res += (fullbit(N) - N)*2;

        printf("%lld\n", res);
    }

    return 0;
}