6498: Xor Sum

时间限制: 1 Sec  内存限制: 128 MB
提交: 27  解决: 13
[提交][状态][讨论版][命题人:admin]

题目描述

You are given a positive integer N. Find the number of the pairs of integers u and v (0≤u,v≤N) 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

输入

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

输出

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

样例输入

3

样例输出

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

按位考虑,因为a xor b = <=a+b,实际上只需要考虑a+b<=n,
但是要求a的每一位不大于b的每一位(关键点,否则u,v会有重复),那么对于两组不同的(a1,b1)和(a2,b2),
如果a1 xor b1等于a2 xor b2,则异或值均为零,
这表明每种(a,b)的取法都会导致不同的(a xor b,a+b)。
 
解法:记dp[i]为满足a+b<=i的(a,b)对的个数,枚举a和b的最低位,记a=2a1+a2,b=2b1+b2,其中a2,b2=0,1且a2<=b2,
那么有a1+b1<=(n-a2-b2)/2,因为a2+b2只能是0,1,2,则有dp[i]=dp[i/2]+dp[(i-1)/2]+dp[(i-2)/2],
那么对于dp[n],可以分析出需要计算的状态数是O((logn)^2)的。
此处对map的用法要熟悉,否则在时间和空间上都会爆!
AC代码:

#include<bits/stdc++.h>
using namespace std;
const long long mod=1e9+7;
map<long long ,long long>dp;
long long solve(long long x)
{
if(dp[x])
{
return dp[x];
}
else
{
return dp[x]=((solve(x/2)+solve((x-1)/2)+solve((x-2)/2)))%mod;
}
}
int main()
{
dp[0]=1;
dp[1]=2;
long long n;
cin>>n;
cout<<solve(n)<<endl;
return 0;
}

最新文章

  1. C++:通过gethostbyname函数,根据服务器的域名,获取服务器IP
  2. MyEclipse中Maven的配置
  3. servlet的配置和上下文
  4. 7、NFC技术:让Android自动运行程序
  5. RecyclerView 下拉刷新上拉加载
  6. 优化大型复杂SQL
  7. Lucene学习总结之三:Lucene的索引文件格式(1)
  8. GDAL1.11版本号对SHP文件索引加速測试
  9. When to use HTML Helper?
  10. FireMonkey Style Designer
  11. 一个带动画的页面底部的TabBar的实现
  12. asp.net MVC实现文章的“上一篇下一篇”
  13. 《剑指offer》平衡二叉树
  14. NPOI颜色对照表
  15. UOJ#132&amp;bzoj4200[Noi2015]小园丁与老司机
  16. 171. Excel表列序号
  17. 【JavaScript 6连载】四、apply和call的用法
  18. php session_start()
  19. 聊聊Http协议
  20. JavaScript小游戏--2048(程序流程图)

热门文章

  1. EF外键保存数据
  2. MS SQL PIVOT数据透视表
  3. js 读本地文件
  4. Tyvj P1520 树的直径
  5. 阿里云服务器新手安装nginx
  6. 微信分账功能与微信支付企业付款相关内容详解(payjs版)
  7. 本机和虚拟机互联 设置静态IP vmware 虚拟网络 桥接 NAT 仅主机 自定义
  8. 黑马旅游网案例 Bug集锦
  9. JMeter(5) JMeter之BeanShell使用
  10. HTTP协议初识