题解:CF2108B SUMdamental Decomposition

· · 题解

思路

为了方便理解,接下来使用表格的形式表示二进制下的 a。例如,

||1|2|3| |:-:|:-:|:-:|:-:| |(4)||1|1| |(2)||1|| |(1)|1||1|

表示 a_1=1,a_2=2+4=6,a_3=1+4=5。
明显,当 n\le \operatorname{popcount}(x) 时,可以构造一组解,使得答案达到最小值 x。以样例 2 27 为例:

||1|2| |:-:|:-:|:-:| |(16)||1| |(8)||1| |(4)||| |(2)|1|| |(1)|1||

可以任意左右移动二进制 1 的位置,只要每个数字不为 0。
当 n>\operatorname{popcount}(x) 时,先观察 x\ge2 的一般情况,以 3 6 为例:

||1|2|3| |:-:|:-:|:-:|:-:| |(8)|||| |(4)|||| |(2)||1|| |(1)|1|1|1|

即使我们尽可能拆散 x,也会还有 n-\operatorname{popcount}(x) 个数字为 0。根据异或的性质,我们可以在两个数字中都添加一个二进制 1(在表格中的加粗部分)。此时答案为 x+n-\operatorname{popcount}(x)+p,其中当 n-\operatorname{popcount}(x) 为奇数时 p=1,否则 p=0。
当 x=1 且 n 为奇数时,类似地,答案为 n。当 n 为偶数,以 2 1 为例:

||1|2| |:-:|:-:|:-:| |(2)|1|1| |(1)|1||

此时在最后一对数字中,二进制位 1 被占用,只能将它们加 2。答案为 n+3。
当 x=0,类似地,n 为偶数时答案为 n,n 为奇数时答案为 n+3。作为例外,n=1 时无解,因为数字必须是正数,且没有其它数字与它异或使异或和为 0。

代码

#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
int help(){
    int n,x;
    cin>>n>>x;
    int b=__builtin_popcountll(x);
    if(n<=b){
        return x;
    }
    else if(x==1){
        if(n%2==1){
            return n;
        }
        else{
            return n+3;
        }
    }
    else if(x==0){
        if(n==1){
            return -1;
        }
        else if(n%2==0){
            return n;
        }
        else if(n%2==1){
            return n+3;
        }
    }
    int ne=n-b;
    if(ne%2==1){
        ne++;
    }
    return x+ne;
}
signed main(){
    int t;
    cin>>t;
    while(t--){
        cout<<help()<<endl;
    }
    return 0;
}