2012-06-08 07:02:45Morris
[UVA][Math] 12444 - Bits and Pieces
Problem A: Bits and Pieces
Let A and B be non-negative integers and let C = A&B and D = A|B. Given C and D, can you find A and B such that the absolute difference (|A-B|) is minimal?
(A&B and A|B are bitwise AND and OR respectively, represented with symbols & and | in the programming languages used in this contest)
Input Format
The input starts with an integer T - the number of test cases (T <= 100). T cases follow on each subsequent line, each of them containing integers C and D (0 <= C,D < 2^31).
Output Format
For each test case, print integers A and B on a line such that A&B=C, A|B=D, A<=B and B-A is minimal. If there are no such A and B, print -1 on the line instead.
Sample Input
3 2 3 3 2 3 15
Sample Output
2 3 -1 7 11
先找不出不可能的解, 之後從大的 bit 開始分, 第一個給 b 其他給 a 即可
#include <stdio.h>
void solve(int c, int d) {
int i, a, b;
for(i = 30; i >= 0; i--) {
if((c&(1<<i)) != 0 && (d&(1<<i)) == 0) {
puts("-1");
return;
}
}
a = c, b = c;
int flag = 0;
for(i = 30; i >= 0; i--) {
if((c&(1<<i)) == 0) {
if((d&(1<<i)) != 0) {
if(flag)
a |= 1<<i;
else
b |= 1<<i;
flag = 1;
}
}
}
printf("%d %d\n", a, b);
}
int main() {
int t, c, d;
scanf("%d", &t);
while(t--) {
scanf("%d %d", &c, &d);
solve(c, d);
}
return 0;
}