题解:AT_abc347_d [ABC347D] Popcount and XOR
题目链接:AT_abc347_d
题目大意
给定非负整数
其中
若存在,则输出
数据范围:
符号说明
解法
观察二进制异或的真值表:
容易想出一个大致的做法:
扫描
- 若
C_i=1 ,则X_i Y_i 一个填0 ,另一个填1 ; - 若
C_i=0 ,则X_i Y_i 都填0 或都填1 。
填写
设变量:
于是有
解得
容易写出以下过程:
for (int i = 0; i <= 60; i ++) {
if ((c >> i) & 1ll) {
if (only_x) {
x |= (1ll << i);
only_x --;
}
else {
y |= (1ll << i);
only_y --;
}
}
else {
if (common) {
x |= (1ll << i);
y |= (1ll << i);
common --;
}
}
}
无解的情况:
-
- 填写结束后
\textbf{only\_x},\textbf{only\_y},\textbf{common} 不为0 。
代码
#include <bits/stdc++.h>
using namespace std;
using longint = long long;
int main() {
int a, b;
longint c;
cin >> a >> b >> c;
int count_c = 0;
for (int i = 0; i <= 60; i ++) {
if ((c >> i) & 1ll) {
count_c ++;
}
}
int only_x = (count_c + (a - b)) / 2;
int only_y = (count_c - (a - b)) / 2;
int common = a - only_x;
longint x = 0, y = 0;
if ((count_c + (a - b)) % 2 != 0)
goto failed;
for (int i = 0; i <= 60; i ++) {
if ((c >> i) & 1ll) {
if (only_x) {
x |= (1ll << i);
only_x --;
}
else {
y |= (1ll << i);
only_y --;
}
}
else {
if (common) {
x |= (1ll << i);
y |= (1ll << i);
common --;
}
}
}
if (common || only_x || only_y)
goto failed;
succeeded:
cout << x << ' ' << y << endl;
return 0;
failed:
cout << -1;
return 0;
}