您的位置:首页 > 其它

codeforces 627 problem A 好题呀,感觉学到了挺多的 亦或

2016-03-24 21:11 477 查看
A. XOR Equation

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

Two positive integers a and b have
a sum of s and a bitwise XOR of x.
How many possible values are there for the ordered pair (a, b)?

Input

The first line of the input contains two integers s and x (2 ≤ s ≤ 1012, 0 ≤ x ≤ 1012),
the sum and bitwise xor of the pair of positive integers, respectively.

Output

Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0.

Examples

input
9 5


output
4


input
3 3


output
2


input
5 2


output
0


Note

In the first sample, we have the following solutions: (2, 7), (3, 6), (6, 3), (7, 2).

In the second sample, the only solutions are (1, 2) and (2, 1).

链接:http://codeforces.com/contest/627/problem/A

这道题目看了我好久还是不会。看了题解以后想了半天才明白,看到别人几分钟就A出来了。中间也一定经过了不少的苦头吧,恩加油吧。

题目的意思呢就是a+b = a^b + (a&b)*2。就是分类讨论一下,下面是题解

For any two integers a and b,
we have 

,
where 

 is
the xor and a&b is the bitwise AND. This is because 

 is
non-carrying binary addition. Thus, we can find a&b = (s - x) / 2 (if this is not an integer, there are no
solutions).

Now, for each bit, we have 4 cases: 

,
and 

.
If 

,
then ai = bi,
so we have one possibility:ai = bi = ai&bi.
If 

,
then we must have ai&bi = 0 (otherwise
we print 0), and we have two choices: ai = 1 and bi = 0 or
vice versa. Thus, we can return 2n,
where n is the number of one-bits in x.
(Remember to subtract 2 for the cases a = 0 or b = 0 if
necessary.)

然后枚举x的原因是因为只要x定了,那么a和b的可能性就定了。然后因为x是a^b,所以a&b=(s-x)/2与x是肯定不会有交集的。

看了大牛的写法以后才知道,原来longlong的定义还可以写成1ll(新手表示c++还在学习的路上)

然后就是当s==x的时候要减去2.因为a和b都要是正数。所以,当a完全等于x的时候或者b完全等于x的时候,a和b都是0,所以这两种不成立,要减去2.

学到了挺多的

#include<cstdio>
#include<cstring>

using namespace std;

typedef long long ll;

ll s, x;

int main(){
while (scanf("%I64d%I64d", &s, &x) == 2){
ll a = (s - x) / 2;
if (x > s || a * 2 + x != s || (x & a) != 0){
printf("0\n");
continue;
}
ll bit = 0;
while (x){
if (x & 1)bit++;
x >>= 1;
}
ll res = 1ll << bit;
if (a == 0) res -= 2;
//if (a == 0) res -= 2;
//printf("bit = %I64d\n", bit);
printf("%I64d\n", res);
}
return 0;
}
</cstring></cstdio>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: