Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 9525 | Accepted: 3420 |
Description
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
Output
Sample Input
2 12
Sample Output
6
Source
题意:给出n到m求n到m内的有多少Round数,转化为二进制后0的个数大于等于1到个数。
转化为计算1到n,1到m的个数,再相减
将一个数x转化为二进制数,那么这个数的最高位一定是1,记录位数cnt,
1、从低位开始直到cnt-1,计算第i位为1,i位之前全部为0时的个数。
2、计算第cnt位时,从高位向低位遍历,当第i位为1时,累加该位为0时的种数。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
#define LL __int64
LL c[33][33] ;
int digit[40] , cnt ;
void get_c()
{
LL i , j ;
memset(c,0,sizeof(c)) ;
c[0][0] = 1 ;
for(i = 1 ; i < 33 ; i++)
{
c[i][0] = 1 ;
for(j = 1 ; j < i ; j++)
c[i][j] = c[i-1][j-1] + c[i-1][j] ;
c[i][j] = 1 ;
}
return ;
}
LL solve(LL temp)
{
LL ans = 0 , i , j , num0 , num1 , k = 0 ;
memset(digit,0,sizeof(digit)) ;
cnt = 0 ;
while( temp )
{
digit[++cnt] = temp%2 ;
if( k == 0 && digit[cnt] == 1 )
k = cnt ;
temp /= 2 ;
}
for(i = 1 ; i < cnt ; i++)
{
//当前位放1
num0 = 0 ;
num1 = 1 ;
for(j = 0 ; j < i ; j++)
{
if( num1+j > (i-1-j)+num0 ) break ;
ans += c[i-1][j] ;
}
}
num0 = 0 ;
num1 = 1 ;
for(j = i-1 ; j > 0 ; j--)
{
if( digit[j] == 0 )//如果这位是0
{
num0++ ;
continue ;
}
//这位是1,先累加放0的,再放1
num0++ ;
for(k = 0 ; k < j ; k++)
{
if( num1+k > (j-1-k)+num0 ) break ;
ans += c[j-1][k] ;
}
num0-- ;
num1++ ;
}
if( num0 >= num1 ) ans++ ;
return ans ;
}
int main()
{
LL n , m ;
get_c() ;
while( scanf("%I64d %I64d", &n, &m) != EOF )
{
printf("%I64d\n", solve(m)-solve(n-1)) ;
}
return 0;
}