题目链接:http://poj.org/problem?id=3252
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
题目理解:
定义一个Roundnumber为该数的2进制数里面0的个数大于等于1的个数。
给你 l , r 。让你求 l 到 r 区间内Roundnumber的个数。
题解:
这个题有两种做法,数位dp和直接用组合数求。
这里讲后一种方法。
很容易知道答案为0到 r+1 的Roundnumber个数减去0到 l 的Roundnumber个数。
之后问题就转换成了求0到k区间内的Roundnumber个数(小于k)
先预处理求出32内的组合数。
求出k的二进制形式(用bin数组来存,bin[0]为长度len),枚举两种情况:长度小于len的和长度等于len的。
1.长度小于len的,因为长度小于len,那么最高位为1,之后就可以枚举长度,且满足条件的,并记录一下。
2.长度等于len的,这时候需要讨论组合所得的数与k的大小,从高位到低位枚举,且记录出现0的位的个数,
枚举时,遇到当前位为0的情况,用zero记录下来,遇到当前位为1的情况,先把当前位看成0,就可以保证小于k。
当当前位位1,把它看成0后,再来组合后面的数。
(1)当前位置i后面允许组合的低位有多少个,我的程序由于bin是从bin[1]开始存储二进制数的,因此 当前位置i后面允许组合的低位有i-1个
(2) 组合前必须要除去前面已出现的0的个数zero
j枚举时从(len[0]+1)/2-(zero+1)开始,因为要保证一半的位为0,而且前面已经确定为0的个数要减掉。
之后再记录一下就行了。
详解请参考:https://blog.csdn.net/lyy289065406/article/details/6648458#commentsedit
#include<iostream>
using namespace std;
int C[32][32]={0};
int bin[35];
void init(){
for(int i=0;i<32;i++){
for(int j=0;j<=i;j++){
if(j==0||i==j) C[i][j]=1;
else C[i][j]=C[i-1][j-1]+C[i-1][j];
}
}
}
void toBin(int n){
bin[0]=0;
while(n){
bin[++bin[0]]=n%2;
n/=2;
}
}
int round(int x){
int sum=0;
toBin(x);
for(int i=1;i<bin[0]-1;i++)
for(int j=i/2+1;j<=i;j++)
sum+=C[i][j];
int zero=0;
for(int i=bin[0]-1;i>=1;i--){
if(bin[i])
for(int j=(bin[0]+1)/2-(zero+1);j<=i-1;j++)
sum+=C[i-1][j];
else zero++;
}
return sum;
}
int main(){
int a,b;
init();
cin>>a>>b;
cout<<round(b+1)-round(a)<<endl;
return 0;
}