题解:ARC208C Mod of XOR

题意

给定 \(C,X\),构造一个 \(n(1\leq n<2^{60})\) 使得 \((n\oplus C)\bmod{n}=X\),或报告无解。多测,\(1\leq T\leq 2\times 10^5\)\(1\leq C,X<2^{30}\)

题解

神人构造题。

显然要有 \(n>X\)。不妨设 \(n\oplus C=qn+X\),分类讨论 \(q\) 的取值。

\(q=0\)

此时 \(n\oplus C=X\Leftrightarrow n=C\oplus X\),于是如果 \((C\oplus X)>X\) 成立,这就是一个合法解。

\(q=1\)

此时 \(n\oplus C=n+X\)。考虑把 \(n\oplus C\) 拆成 \(n+C-2(n\operatorname{and} C)\),这样就变成了 \(C-2(n\operatorname{and} C)=X\)。设 \(d=C-X\)

  • \(d\) 是奇数或 \(d<0\),则 \(q=1\) 的 case 无解。
  • \(d\) 是非负偶数,但是 \(\left(\dfrac{d}{2}\operatorname{and} C\right)\neq \dfrac{d}{2}\),则同样无解。
  • \(d\) 是非负偶数,且 \(\left(\dfrac{d}{2}\operatorname{and} C\right)=\dfrac{d}{2}\),我们令 \(n=\left(\dfrac{d}{2}\operatorname{and} C\right)+2^{30}\) 即可。

\(q\geq 2\)

我们指出,若上面两种 case 都无解,则这种 case 也无解。

证明:反证法,假设 \(0\leq q\leq 1\) 的 case 都无解,且 \(q=2\) 的 case 有解。很显然 \(qn+X=(n\oplus C)\leq n+C\),因此 \(C\geq (q-1)n+X>2X\)。而注意到 \(q=0\) 的 case 无解等价于 \((C\oplus X)\leq X\),这和 \(C>2X\) 矛盾。\(\Box\)


按照上述分类讨论直接实现即可,时间复杂度 \(\mathcal{O}(T)\)

代码

#include <bits/stdc++.h>

using namespace std;

#define lowbit(x) ((x) & -(x))
typedef long long ll;
typedef pair<int, int> pii;

template<typename T> inline void chk_min(T &x, T y) { x = min(x, y); }
template<typename T> inline void chk_max(T &x, T y) { x = max(x, y); }

int T, c, x;

int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> T;
    while (T--) {
    	cin >> c >> x;
    	int n = c ^ x;
    	if (n > x) { cout << n << '\n'; continue; }
    	int d = c - x;
    	if (d >= 0 && (~d & 1)) {
    		d >>= 1;
    		if ((d & c) == d) cout << (d | (1ll << 30)) << '\n';
    		else cout << "-1\n";
    	} else cout << "-1\n";
    }
    return 0;
}
posted @ 2025-10-20 22:07  P2441M  阅读(5)  评论(0)    收藏  举报