24h購物| | PChome| 登入
2012-06-08 07:02:45| 人氣2,083| 回應0 | 上一篇 | 下一篇

[UVA][Math] 12444 - Bits and Pieces

推薦 0 收藏 0 轉貼0 訂閱站台

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;
}

台長: Morris
人氣(2,083) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][path] 452 - Project Scheduling
此分類上一篇:[UVA] 11094 - Continents

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文