The cows, as you know, have no fingers or thumbs and thus are unable to play Scissors, Paper, Stone' (also known as 'Rock, Paper, Scissors', 'Ro, Sham, Bo', and a host of other names) in order to make arbitrary decisions such as who gets to be milked first. They can't even flip a coin because it's so hard to toss using hooves.
They have thus resorted to "round number" matching. The first cow picks an integer less than two billion. The second cow does the same. If the numbers are both "round numbers", the first cow wins,
otherwise the second cow wins.
A positive integer N is said to be a "round number" if the binary representation of N has as many or more zeroes than it has ones. For example, the integer 9, when written in binary form, is 1001. 1001 has two zeroes and two ones; thus, 9 is a round number. The integer 26 is 11010 in binary; since it has two zeroes and three ones, it is not a round number.
Obviously, it takes cows a while to convert numbers to binary, so the winner takes a while to determine. Bessie wants to cheat and thinks she can do that if she knows how many "round numbers" are in a given range.
Help her by writing a program that tells how many round numbers appear in the inclusive range given by the input (1 ≤ Start < Finish ≤ 2,000,000,000).
2 12
6
【题解】
大致题意,给定一个区间,寻找区间内二进制表示法中0的个数大于等于1的个数的数的个数。
分析:把给定区间的上限用二进制表示出来,其长度就是二进制表示上限,举个例子吧,1011011001,假定其为区间上限的二进制表示,长度为10,所以说,任何长度小于10的二进制数都没有它大,所以我们就可以从长度为1开始枚举,长度为i=1的只有二进制表示的1,只有一个1,没有0,所以满足题意,继续遍历,长度i>=2时要注意,最高位必须是1,所以也就是说最高位是已知的,在剩下的i-1 位中按照排列组合法求满足条件的数的组合数,因为已经有了最高位的1,所以算的时候只要0的个数大于等于1的个数加1,。
这些完了就是最麻烦的地方了,就是长度等于上限长度,但是数值小于等于上限数值的数的个数了,这个就要挨个遍历寻找了,具体看代码:
还有一点,组合公式:C[i][j]=C[i-1][j-1]+C[i-1][j];
顺便说一下,这道题int不会爆,我看见好多题解上都给的LL ,没必要。
【AC代码】
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=2e9+7;
int m,n;
int dp[50][50];
int sum[50];
void init()
{
memset(dp,0,sizeof(dp));
for(int i=0;i<50;++i)
for(int j=0;j<=i;++j)
if(j==0 || i==j) dp[i][j]=1;
else dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
}
int solve(int x)
{
if(x<=1) return 0;
int ans=0,zero=0,one=0,len=0;
while(x)
{
sum[len++]=x%2;
if(x%2) one++;
else zero++;
x/=2;
}
for(int i=len-1;i>0;--i) //从第一位到最高位的次位依次遍历
{
if(i%2)//总数位为奇数 除去最高位的1,就剩下偶数位了
ans+=((1<<(i-1))-dp[i-1][(i-1)/2])/2; //二进制中0和1个数不想等的数目,总情况减去剩余位中1和0相等的情况,比如i=5,剩下4位中两个0两个1的组合数
else
ans+=(1<<(i-1))/2;//总位数为偶数i,最高位为1,剩下的i-1位的组合数
}
if(zero>=one)//数本身二进制表示也满足条件
ans++;
zero=0,one=1;
for(int i=len-2;i>=0;--i)//
{
if(sum[i]==0)
zero++;
else //遍历满足条件的插入法,
{
for(int j=i;j>=0 && j+zero+1 >=i-j+one;--j)
{
ans+=dp[i][j];
}
one++;
}
}
return ans;
}
int main()
{
init();
while(~scanf("%d%d",&m,&n))
{
printf("%d\n",solve(n)-solve(m-1));
}
return 0;
}