Xor Sum AtCoder - 2272


Time limit : 2sec / Memory limit : 256MB

Score : 600 points

Problem Statement

You are given a positive integer N. Find the number of the pairs of integers u and v (0≦u,vN)such that there exist two non-negative integers a and b satisfying a xor b=u and a+b=v. Here, xor denotes the bitwise exclusive OR. Since it can be extremely large, compute the answer modulo 109+7.

Constraints

  • 1≦N≦1018

Input

The input is given from Standard Input in the following format:

N

Output

Print the number of the possible pairs of integers u and v, modulo 109+7.


Sample Input 1

Copy

3

Sample Output 1

Copy

5

The five possible pairs of u and v are:

  • u=0,v=0 (Let a=0,b=0, then 0 xor 0=0, 0+0=0.)

  • u=0,v=2 (Let a=1,b=1, then 1 xor 1=0, 1+1=2.)

  • u=1,v=1 (Let a=1,b=0, then 1 xor 0=1, 1+0=1.)

  • u=2,v=2 (Let a=2,b=0, then 2 xor 0=2, 2+0=2.)

  • u=3,v=3 (Let a=3,b=0, then 3 xor 0=3, 3+0=3.)


Sample Input 2

Copy

1422

Sample Output 2

Copy

52277

Sample Input 3

Copy

1000000000000000000

Sample Output 3

Copy

787014179

题目链接

题目大意:给出一个数字n,寻找两个数字uv,使得对于0<=u,v<=n,有a+b=u,a^b=v,求uv的对数

题解:是一道dp题,由于不是很擅长dp加上逻辑能力欠缺,看这道题看了大半天……是的,我看了大半天题解才看懂。

由于a+b = (a&b)<<1 + a^b,故可知a^b定然小于a+b,故本题可以化为寻找对于a+b<=n中ab的个数。

首先可以使用暴力的手段得知,当n=0的时候,答案为1,n=1的时候,答案为2。对于a与b(化作二进制来看),两者的末位和有0,1,2三种情况,设a+b=x,令a = a1*2+a2, b = b1*2+b2,a2+b2即为两者的末位和,又有x<=n,故a1+a2<=(n-a1-a2)/2,可以得出递推式 dp[x] = dp[x/2] + dp[(x-1)/2] + dp[(x-2)/2];

代码如下

#include<iostream>
#include<cstdio>
#include<map>
#include<sstream>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
const long long maxn = 1e18+7;
const int mod = 1e9+7;
map<long long, long long>dp;
long long func(long long x)
{
    if(dp[x])return dp[x];
    return dp[x] = (func(x/2) + func((x-1)/2) + func((x-2)/2))%mod;
}

int main()
{
    long long n;
    cin >> n;
    dp[0] = 1;
    dp[1] = 2;
    cout << func(n) << endl;
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值