zoukankan      html  css  js  c++  java
  • Xor Sum

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

  • 相关阅读:
    ajax_注册
    mysql 二
    mysql基础
    django数据库批量创建
    私有属性
    mysql操作
    @property @classmethod @staticmethod
    python中的__new__方法
    员工信息表-装逼版
    三级菜单
  • 原文地址:https://www.cnblogs.com/lglh/p/9133661.html
Copyright © 2011-2022 走看看