Round Numbers
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 5077 Accepted: 1736
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
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
Source
USACO 2006 November Silver
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int limit[50];
int f[50][50];
int sum[50][50];
int calc(int num){
int i, j, k, len, ans;
if (num <= 0) return 0;
for (len = 1; num; len++){
limit[len] = num & 1;
num >>= 1;
}
limit[len] = 0;
ans = 0;
for (i = len - 2; i > 0; i--){
j = (i + 1) / 2;
ans += sum[i - 1][j];
}
k = 0;
/*这里定义为前面出现过k个0
若定义为后面可以少k个0,则看上去只考虑长度为i的
得到j = i / 2 - k - 1,但这是错的
因为没有把i和前面多的k个0放一块考虑,例如
...110, i = 3, k = 1,时
需要i / 2 = 1个0,但这时k告诉说我帮你顶一个,看样子就不需要0了
但是不作为0的空缺就会被填上1,于是就有2个1,实际需求变为2个0,而不是1个0
*/
for (i = len - 2; i > 0; i--){
if (limit[i] == 1){
j = len / 2 - k - 1;
if (j < 0) j = 0;
ans += sum[i - 1][j];
}else k++;
}
if (k >= len / 2) ans++;
return ans;
}
int main(){
int i, j, bg, ed;
memset(f, 0, sizeof(f));
memset(sum, 0, sizeof(sum));
f[0][0] = 1;
sum[0][0] = 1;
for (i = 1; i < 31; i++){
f[i][0] = 1;
for (j = 1; j <= i; j++){
f[i][j] = f[i - 1][j] + f[i - 1][j - 1];
}
sum[i][i] = 1;
for (j = i - 1; j >= 0; j--){
sum[i][j] = sum[i][j + 1] + f[i][j];
// printf("s[%d][%d] = %d\n", i, j, sum[i][j]);
}
}
while(scanf("%d%d", &bg, &ed) != EOF){
bg = calc(bg - 1);
ed = calc(ed);
printf("%d\n", ed - bg);
}
return 0;
}