Round Numbers
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, 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 |
题意:给出区间[a,b],求其中二进制表示时0的数量>=1的数量的数个数(不能算前导零)。
解法:dp[pos][num(0)-num(1)+32]
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)
#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)
#define mes(a,x,s) memset(a,x,(s)*sizeof a[0])
#define mem(a,x) memset(a,x,sizeof a)
#define ysk(x) (1<<(x))
typedef long long ll;
typedef pair<int, int> pii;
const int INF =0x3f3f3f3f;
int bit[35],dp[35][70];
int dfs(int pos,int num,int lead,int limit)
{
if(pos==-1) return num>=32;
if(!lead&&!limit&&~dp[pos][num]) return dp[pos][num];
int ans=0;
int up=limit?bit[pos]:1;
for0(i,up+1)
{
if(lead&&!i ) ans+=dfs(pos-1,num ,lead,limit&&i==bit[pos] );
//如果现在为0,因为之前lead为0,那么lead以后为0。限制方面可能从有限制到无限制。
else ans+=dfs(pos-1,num+ (i?-1:1),lead&&!i ,limit&&i==bit[pos]);
}
if(!lead&&!limit) dp[pos][num]=ans;
return ans;
}
int solve(int x)
{
int nbit=0;
while(x)
{
bit[nbit++]=x&1;
x>>=1;
}
return dfs(nbit-1,32,1,1);
}
int main()
{
std::ios::sync_with_stdio(false);
mem(dp,-1);
int a,b;
while(cin>>a>>b)
{
printf("%d\n",solve(b)-solve(a-1));//题目要求的是正数,但是solve(b)和solve(a-1)均包含0,故不影响。
}
return 0;
}