http://poj.org/problem?id=3252

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).

 

题意:统计闭区间内满足某数的二进制形式0的个数>=1的个数这一条件的数字的个数。

思路:数位dp,状态为(pos位,0的个数比1的个数多多少)

0有可能比1少,故向上偏移32,[-32,32]~[0,64]。

需要前导0,因为0001101这样的数前面的0不算。

#include<cstring>
#include<iostream>
using namespace std;

int T,A,B,all;
int a[40],dp[40][70];

int dfs(int pos,int sta,bool lead,bool limit)
{
	if(pos==-1)return sta>=32;
	if(!limit&&!lead&&dp[pos][sta]!=-1)return dp[pos][sta];
	int up= (limit?a[pos]:1);
	int ans=0;
	for(int i=0;i<=up;i++)
	{
		if(lead&&i==0)ans+=dfs(pos-1,32,1,0);
		else ans+=dfs(pos-1,sta+(i==0?1:-1),0,limit&&i==a[pos]);
	}
	if(!limit&&!lead)dp[pos][sta]=ans;
	return ans;
}

int solve(int n)
{
	int pos=0;
	while(n)
	{
		a[pos++]=(n&1);
		n>>=1;
	}
	return dfs(pos-1,32,1,1);
}

int main()
{
//	freopen("input.in","r",stdin);
	memset(dp,-1,sizeof(dp));
	while(cin>>A>>B)cout<<solve(B)-solve(A-1)<<endl;
	return 0;
}