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
- 1
- 2
- 3
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 (1 ≤ l ≤ r ≤ 10181 ≤ l ≤ r ≤ 1018). 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.
算法分析:
题意:
给你一个范围[A,B],让你判断范围内所有数是否为平衡数,是平衡数的条件为:
1、对于每一位上的数字,如果是偶数,则必须出现奇数次。
2、对于每一位上的数字,如果是奇数,则必须出现偶数次。
分析:
先枚举所有可能的长度,然后枚举周期k 的大小,对于小于极限长度的长度,那么直接可以用1<<(j-1)(如果枚举的数字长度小于n,那么该种长度下循环节为j的所有方案都可以取到,共2^j种方案,同理删去最高位为0的2^{j-1}种方案,故dp[j]=2^j-2^{j-1}=2^{j-1}))(比如k=3,111,110,100,101,四种)算出,因为假如现在枚举的k为j,相当于处理最高位一样,剩下的可以随便变化;对于极限值,用cal计算
注意:k为满足条件的循环长度(当前长度可以整除k)。而且还要去掉重复的,比如当长度为6时,循环长度为2,3的数均会重复计算,当数的长度为len时,则在限制下,计算满足条件的数
代码实现:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL num[100],dp[100];
LL getmaxlen(int len,int k,LL m) //对于最高位情况的处理
{
LL x=0;
for(int i=0;i<k;i++) x<<=1,x+=num[len-i]; //计算循环节的大小,取最大数二进制前几位
LL y=x;
for(int i=1;i<len/k;i++) //len%k一定等于0,solve函数
//y=y*(2^k)
y<<=k,y+=x; //这里y是把极值生成了
cout<<len<<" "<<y<<" "<<k<<" "<<m<<" "<<x<<endl;
return x-(1<<(k-1))+1/*此处加1是因为全0的原因*/-(y>m);
/*对于当前枚举的数字长度len和循环节长度k,一个小循环节的值可以取0~x这x+1种,但是其中有2^{k-1}种方案是第一位为0的,这些要去掉(否则会出现前置0);如果最大值(也就是y)超过n,那么只要把一个小循环节取值上限从x变为x-1就可以保证最大值是不超过n的,所以减去了(y>n)*/
//将极限值与限定值相比较,从而判断极值是否在限定范围内
}
LL solve(LL m)
{
int len;
LL n=m,ans=0;
for(len=0;n;n>>=1) num[++len]=n&1;
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); //长度小于len
else dp[j]=getmaxlen(len,j,m);
for(int k=1;k<j;k++) //这里去重
if(!(j%k)) dp[j]-=dp[k];
ans+=dp[j];
}
}
return ans;
}
int main()
{
LL l,r;
scanf("%lld%lld",&l,&r);
printf("%lld\n",solve(r)-solve(l-1));
return 0;
}