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).
Input
Line 1: Two space-separated integers, respectively Start and Finish.
Output
Line 1: A single integer that is the count of round numbers in the inclusive range Start… Finish
Sample Input
2 12
Sample Output
6
题意:一个十进制数化成2进制,要是二进制数里0的个数不小于1的个数称为圆数,现在给出一个区间(n,m),问里面有多少圆数。
解题思路:将数转换为二进制数后,直接比较当前0的数量是否不小于1的数量,dp[pos][sum]表示在pos位上0的数量减去1的数量不少于num的方案数,需要提前将sum赋一个初值,而且本题是计算二进制中0,1的个数,所有在记忆化的时候需要考虑前导0的影响。代码注释较多,容易懂。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
int dp[50][100];//2e9大概30多位,直接开50.
int a[50];
int dfs(int pos,int sum,int lead,int limit){
if(pos==-1)
return sum>=50;//判断0的个数是否大于1的个数
if(!limit&&!lead&&dp[pos][sum]!=-1)//要统计0的数量,前导零是有影响的
return dp[pos][sum];
int up=limit?a[pos]:1;//二进制位上最大位1.
int tmp=0;
for(int i=0;i<=up;i++){
if(i==0){
if(lead)//前一位为0,当前位为1,sum的值不变
tmp+=dfs(pos-1,sum,1,limit&&i==a[pos]);
else
tmp+=dfs(pos-1,sum+1,0,limit&&i==a[pos]);//当前位为0,sum+1.
}
else
tmp+=dfs(pos-1,sum-1,0,limit&&i==a[pos]);//当前位为1,sum-1.
}
if(!limit&&!lead)//跟上面的记忆化一样需要考虑前导0的影响
dp[pos][sum]=tmp;
return tmp;
}
int solve(int n)
{
int len=0;
while(n)
{
a[len++]=n&1;
n>>=1;
}
return dfs(len-1,50,1,1);//处理成2进制数,把sum赋一个初值,
//中间某个pos位上sum可能为负数(这不一定是非法的,因为我还没枚举完嘛,只要最终的sum>=0才能判合法,中途某个pos就不一定了)
}
int main()
{
int n,m;
memset(dp,-1,sizeof dp);//多组输入,初始化放外面,会快一点
while(~scanf("%d%d",&n,&m)){
printf("%d\n",solve(m)-solve(n-1));
}
return 0;
}