Time Limit: 2000MS | Memory Limit: 65536K | |
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
/*
ID: j.sure.1
PROG:
LANG: C++
*/
/****************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <climits>
#include <iostream>
#define INF 0x3f3f3f3f
using namespace std;
/****************************************/
int dp[35][70][2];
int num[35], cnt;
int dfs(int len, int diff, bool one, bool bnd)
{
if(len == 0) {
if(diff >= 35) {
return 1;
}
return 0;
}
if(!bnd && dp[len][diff][one] != -1)
return dp[len][diff][one];
int lim = (bnd ? num[len] : 1);
int ret = 0;
for(int i = 0; i <= lim; i++) {
int nd;
if(one||i)//这里WA了一次,因为用了one(前一个数是否出现1)来判断
nd = (i == 0 ? 1 : -1);
else
nd = 0;
ret += dfs(len-1, diff + nd, one || i, bnd&&i==lim);
}
if(!bnd) dp[len][diff][one] = ret;
return ret;
}
int Solve(int x)
{
cnt = 0;
while(x) {
num[++cnt] = x&1;
x >>= 1;
}
return dfs(cnt, 35, false, true);//以35作为初始值,防止下标为负
}
int main()
{
#ifdef J_Sure
// freopen("000.in", "r", stdin);
// freopen(".out", "w", stdout);
#endif
int l, r;
memset(dp, -1, sizeof(dp));
while(~scanf("%d%d", &l, &r)) {
printf("%d\n", Solve(r) - Solve(l-1));
}
return 0;
}