跳到正文

题解

题解:CF2108B SUMdamental Decomposition

wangboyue_740325约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年5月4日
收录
2025年12月12日
更新
2026年11月22日
篇幅
约 3 分钟
获赞
1
题目
CF2108B

版本

  1. v1当前

思路

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

123
(4)11
(2)1
(1)11

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

12
(16)1
(8)1
(4)
(2)1
(1)1

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

123
(8)
(4)
(2)1
(1)111

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

12
(2)11
(1)1

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

代码

C++
#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;
}
原文
存档评论1 条抓取于