题解:AT_arc208_c [ARC208C] Mod of XOR
神秘小构造。
观察式子
所以可以考虑
- 若不取模,则
n \oplus c < n ,则n \oplus c = x ,即n = x \oplus c ,于是若x \oplus c > x 时,n 必定有解。 - 若取模,则
n \oplus c = n + x ,考虑解这个方程。
异或等于二进制不进位加法。注意到等式两侧为异或和加法。可以从进位角度思考。
因为
否则,考虑构造一个
因为加法存在进位,于是从低位往高位考虑。
记
若当前的
否则,考虑
若为
若为
处理完所有位数后,可能存在
:::info[code]
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
typedef long long ll;
typedef pair<int, int> pi;
#define endl '\n'
bool check (ll n, int x, int c) {
return (n ^ c) % n == x;
}
signed main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t --) {
int x, c;
cin >> c >> x;
if ((x ^ c) > x) {
cout << (x ^ c) << endl;
} else {
if (c < x) { // n ^ c <= n + c -> n + c <= n + x -> 无解
cout << -1 << endl;
} else { // n ^ c = x + n
ll n = (1ll << 35);
bool flag = 1;
for (int i = 0; i < 30; i ++) {
int v1 = (c >> i & 1), v2 = (x >> i & 1);
int u1 = (c >> (i + 1) & 1), u2 = (x >> (i + 1) & 1);
if (v1 != v2) {
flag = 0;
break;
}
if (v1) {
if (u1 != u2) n += (1 << i), x += (1 << i + 1); // 加法进位
}
}
// cout << check(n, x, c) << endl;
if(flag) cout << n << endl;
else cout << -1 << endl;
}
}
}
return 0;
}
:::