1. 程式人生 > >codeforces215 E. Periodical Numbers(數位dp)

codeforces215 E. Periodical Numbers(數位dp)

E. Periodical Numbers
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

A non-empty string s is called binary, if it consists only of characters “0” and “1”. Let’s number the characters of binary string s from 1 to the string’s length and let’s denote the i-th character in string s as si.

Binary string s with length n is periodical, if there is an integer 1 ≤ k < n such that:

k is a divisor of number n
for all 1 ≤ i ≤ n - k, the following condition fulfills: si = si + k 

For example, binary strings “101010” and “11” are periodical and “10” and “10010” are not.

A positive integer x is periodical, if its binary representation (without leading zeroes) is a periodic string.

Your task is to calculate, how many periodic numbers are in the interval from l to r (both ends are included).
Input

The single input line contains two integers l and r (1lr1018). The numbers are separated by a space.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output

Print a single integer, showing how many periodic numbers are in the interval from l to r (both ends are included).
Sample test(s)
Input

1 10

Output

3

Input

25 38

Output

2

Note

In the first sample periodic numbers are 3, 7 and 10.

In the second sample periodic numbers are 31 and 36.

思路:假如說現在處理的是1-x,那麼列舉所有可能的長度,然後列舉k 的大小,對於小於極限長度的長度,那麼直接可以用1<<(j-1)算出,因為假如現在列舉的k為j,相當於處理最高位一樣,剩下的可以隨便變化;對於極限值,用cal計算

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=70;
int dig[maxn];
LL x,y;
LL dp[maxn];
LL cal(int len,int k,LL x)
{
    LL a=0,b=0;
    for(int i=0;i<k;i++)
        a+=(dig[len-i]<<(k-1-i));
    b=a;
    for(int i=1;i<len/k;i++)
        b<<=k,b+=a;
    return a-(1<<(k-1))+1/*此處加1是因為全0的原因*/-(b>x);
}
LL solve(LL x)
{
    int len=0;
    LL n=x;
    while(x)
    {
        dig[++len]=x%2;
        x>>=1;
    }
    LL ans=0;
    for(int i=2;i<=len;i++)
    {
        memset(dp,0,sizeof(dp));
        for(int j=1;j<i;j++)
        {
            if(i%j)continue;
            if(i<len)dp[j]=(1<<(j-1));
            else dp[j]=cal(len,j,n);
            for(int k=1;k<j;k++)
                if(j%k==0)dp[j]-=dp[k];
            ans+=dp[j];
        }
    }
    return ans;
}
int main()
{
    scanf("%I64d%I64d",&x,&y);
    printf("%I64d\n",solve(y)-solve(x-1));
    return 0;
}