SCAU2020春季个人排位赛div2 #5--B

题目描述

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).

说下这题的思路

这题的解法涉及到一个公式(我也是比赛完后才知道的害),
a+b = a&b2 + a^b,这个公式中a&b2相当于进位,a ^b相当于未加进位时的值。
有了这个公式了以后,我们就可以轻松解这道题目了,首先a+b和a^b的值我们是可以直接通过输入得到的。我们将这个公式移项,即可得到(a+b)-a ^b=a&b2,接着我们只需要讨论a ^b和a&b的位数就好。
首先给出两个讨论:
第一个是a^b=0,这种情况下对应的a和b的值要么是00,要么是11,可以通过a&b的值来直接判断,所以这个情况的唯一确定的。
第二个是a^b=1,这种情况下对应的a和b的值有两种情况(不能通过a&b来直接判断),要么是01,要么是10,但是要注意,此处的a&b!=1(这是作为合法性的判断,不合法的话直接输出0),合法的话ans
=2;
这里需要说明两个比较特殊的情况:
第一种是s==x,这种情况下s^x二进制全为0,但是题目说明了,数全为正数,所以就去掉了0这种可能,因为0这种可能对应两种情况,比如说5,有110 000,或000 110 两种,因为不能有0的出现,所以不存在这两种情况,所以在最后的ans要减2.
第二种是(a+b-a ^ b)%2!=1,因为(a&b)*2=(a+b-a^b),因为(a&b)*2所以左移了一位,所以(a+b-a ^b)的最低为不是1,若不符合,则说明不合法,直接输出0.

所以这道题目只需要记录是否有s==x,并且判断是否合法,不合法则输出零,合法则按上述的讨论进行统计。
最后输出答案即可。

代码如下:

#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
ll s,x;
bool flag=0;
int main()
{
    ll ans=1;
    cin>>s>>x;
    if(s==x) flag=1;
    s-=x;
    if(s%2==1)
    {
        cout<<"0"<<endl;
        return 0;
    }
    s=s>>1;
    for(int i=0;i<64;i++)
    {
        ll a,b;
        a=(s>>i)&1;
        b=(x>>i)&1;
        cout<<"a="<<a<<"      b="<<b<<endl;
        if(a==b&&a==1)
        {
            cout<<"0"<<endl;
            return 0;
        }
        if(b==1) ans*=2;
    }
    if(flag) ans-=2;
    cout<<ans<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_春与修罗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值