Vlad and a Pair of Numbers
题目描述:
Vlad found two positive numbers \(a\) and \(b(a,b>0)\). He discovered that \(a⊕b=\frac{a+b}{2}\), where \(⊕\) means the bitwise exclusive OR , and division is performed without rounding..
Since it is easier to remember one number than two, Vlad remembered only \(a⊕b\), let's denote this number as \(x\) . Help him find any suitable \(a\) and \(b\) or tell him that they do not exist.
输入描述:
The first line of the input data contains the single integer \(t(1≤t≤10^4)\) — the number of test cases in the test.
Each test case is described by a single integer \(x (1≤x≤2^{29})\) — the number that Vlad remembered.
输出描述:
Output \(t\) lines, each of which is the answer to the corresponding test case. As the answer, output \(a\) and \(b(0<a,b≤2^{32})\), such that \(x=a⊕b=\frac{a+b}{2}\)
. If there are several answers, output any of them. If there are no matching pairs, output \(-1\).
样例:
input:
6
2
5
10
6
18
36
output:
3 1
-1
13 7
-1
25 11
50 22
AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
// 对于一个数x,某个位上是1的情况下
// 让a在对应位上为1,b在对应位上为0
// 而对于x某个位上是0的情况下
// 先贪心地让a,b对应位都为1
// 最后判断一下是否符合题意即可
void solve()
{
int x;
cin >> x;
// a和b必是一个大于x,一个小于x
int a = x;
int b = 0;
for(int i = 29; i >= 0; i --)
{
// 防止前面有0的情况,比如10 = (000...00001010)
if(x & (1 << i) > 0)
continue;
// 在某个位是0的情况下,假设a,b对应位都为1,所以就加上两倍的(1 << i)
// 只要小于等于2 * x就可以
if(2 * x >= (2 << i) + a + b)
{
a += (1 << i);
b += (1 << i);
}
}
if(a + b == 2 * x && (a ^ b) == x)
cout << a << ' ' << b << '\n';
else
cout << -1 << '\n';
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int T;
cin >> T;
while(T --)
solve();
return 0;
}