Codeforces Good bye 2015 B. New Year and Old Property dfs 数位DP

B. New Year and Old Property

题目连接:

http://www.codeforces.com/contest/611/problem/B

Description

The year 2015 is almost over.

Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 201510 = 111110111112. Note that he doesn't care about the number of zeros in the decimal representation.

Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?

Assume that all positive integers are always written without leading zeros.

Input

The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 1018) — the first year and the last year in Limak's interval respectively.

Output

Print one integer – the number of years Limak will count in his chosen interval.

Sample Input

5 10

Sample Output

2

Hint

题意:

给你l,r区间,问你[l,r]中,二进制中只含有1个0的数有多少个

题解

直接dfs跑就好了,dfs(int x,int flag)表示现在是x,这个数里面是否只含有1个0。当然,也可以数位Dp(误。

dfs代码

#include<bits/stdc++.h>
using namespace std;

long long ans = 0;
long long l,r;
void dfs(long long x,int flag)
{
    if(x>r)return;
    if(x>=l&&x<=r&&flag==1)
        ans++;
    if(flag==0)dfs(x*2,1);
    dfs(x*2+1,flag);
}

int main()
{
    cin>>l>>r;
    dfs(1,0);
    cout<<ans<<endl;
}

数位DP 代码

#include<bits/stdc++.h>
using namespace std;


long long pre[100];
long long dp[100][5][5];
int vis[100][5][5];
long long dfs(long long x,int flag1,int flag2)
{
    if(x==-1)
    {
        if(flag2==2)
            return 1;
        else
            return 0;
    }
    if(vis[x][flag1][flag2])
        return dp[x][flag1][flag2];
    vis[x][flag1][flag2]=1;
    long long ans = 0;
    int T = 0;
    if(flag1==1)T = 1;
    else T = pre[x];
    for(int i=0;i<=T;i++)
    {
        int k = flag1 | (i<T);
        if(flag2 == 1)
        {
            if(i==1)
                ans = ans + dfs(x-1,k,1);
            else
                ans = ans + dfs(x-1,k,2);
        }
        else if(flag2==0)
        {
            if(i==1)
                ans = ans + dfs(x-1,k,1);
            else
                ans = ans + dfs(x-1,k,0);
        }
        else
        {
            if(i!=0)
                ans = ans + dfs(x-1,k,2);
        }
    }
    dp[x][flag1][flag2]=ans;
    return ans;
}
long long solve(long long x)
{
    memset(vis,0,sizeof(vis));
    for(long long i=62;i>=0;i--)
    {
        if((x>>i)&1LL)pre[i]=1;
        else pre[i]=0;
    }
    return dfs(60,0,0);
}

int main()
{
    long long a,b;
    cin>>a>>b;
    cout<<solve(b)-solve(a-1)<<endl;
}
posted @ 2015-12-31 11:26  qscqesze  阅读(570)  评论(0编辑  收藏  举报