跳到正文

题解

CF1748D ConstructOR 题解

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
获赞
9
题目
CF1748D

版本

  1. v1当前

可能更好的食用体验

既然题目中用到了位运算,那我们就用二进制来解决这道题。

1.判无解

观察 3 4 63\,4\,6 这个样例,我们将其分解二进制:

(3)10=(11)2(4)10=(100)2(6)10=(110)2\begin{aligned} (3)_{10} &= (11)_2 \\ (4)_{10} &= (100)_2\\ (6)_{10} &= (110)_2\\ \end{aligned}

我们设 lowbit⁡(x)\operatorname{lowbit}(x) 表示 xx 最末尾的 11 在第几位,那么我们可以发现一条性质:lowbit⁡(d)≤lowbit⁡(aor⁡b)\operatorname{lowbit}(d)\le\operatorname{lowbit}(a\operatorname{ or }b)。如果不满足,那么一定无解。

2.构造 xx

我们来分析样例中的第一组数据:

a=1100b=100111d=101\begin{aligned} a &= 1100\\ b &= 100111\\ d &= 101\\ \end{aligned} 1100100111—————101101    101                  —————10101111\begin{aligned} 1100&\\ 100111&\\ \text{---------------}\\ 101&\\ 101\;\;&\\ 101\;\;\;\;\;\;\;\;\;\\ \text{---------------}\\ 10101111 \end{aligned}

我们可以发现 xx 有若干个 dd 相加得到,并且 (aor⁡x)=x(a\operatorname{or}x )=x,(bor⁡x)=x(b\operatorname{or}x )=x,所以一定满足 d ∣ (aor⁡x)d\,|\,(a\operatorname{or}x) 且 d ∣ (aor⁡x)d\,|\,(a\operatorname{or}x)。

xx 的构造方法如上所示。设 c←(aor⁡b)c\gets (a\operatorname{or}b),则对于 cc 的每 ii 位二进制位为 11,如果 xx 的第 ii 位也为 11 则跳过,否则 x←x+2i−lowbit⁡(d)x\gets x+2^{i-\operatorname{lowbit}(d)}。

Code

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T,a,b,d,k,x;
void solve(){
	cin>>a>>b>>d;
	k=x=0;//k表示lowbit(d)
	while((d>>k&1)^1)k++;
	for(int i=0;i<30;i++)
		if( ((a|b)>>i&1) && (x>>i&1)==0 )
			if(i<k)return void(puts("-1"));//判无解
			else x+=(d<<i-k);
	cout<<x<<endl;
}
signed main(){
	cin>>T;
	while(T--)solve();
	return 0;
}

P.s. 应为构造方式比较特殊,所以输出会和样例输出不一样,不要像我一样傻傻的为此去调了二十分钟。

样例输出

代码
175
14
-1
-1
2
27
64446
143838208856161791
原文