Round Numbers POJ - 3252 数位DP

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

题意:给出区间[L,R], 统计区间[L,R]有多少个数的2进制中0的个数不小于1的个数。

思路:既然我们要求0的个数不小于1的个数,我们就令dp[pos][st]表示pos位数中0与1的差为st的数的个数,st为0与1的差,因此可能为负,而数组下标不能为负,用hash法,令0与1的差为0时st==32,因此无论如何st>=0。该题需要注意的一点是前导0对该题目有影响,例如0010中0与1的差值为-2,而实际上0010=10,0与1的差值为0,因此我们要处理前导0.

#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
ll dp[100][70],dit[100];
ll dfs(int pos,int st,int lead,int limit)
{
	if(pos<0) return st>=32;
	if(!limit&&!lead&&dp[pos][st]!=-1) return dp[pos][st];
	int up=limit?dit[pos]:1;//上限为1,因为只有1,0
	ll ans=0;
	for(int i=0;i<=up;i++)
	{
		if(lead&&i==0)
			ans+=dfs(pos-1,st,lead,limit&&i==dit[pos]);
		else
			ans+=dfs(pos-1,st+(i==0?1:-1),lead&&i==0,limit&&i==dit[pos]);
	}
	if(!limit&&!lead) return dp[pos][st]=ans;
	return ans;
}
ll solve(ll x)
{
	int len=0;
	while(x)//转化为二进制,并保存在一个数组里
	{
		dit[len++]=x&1;
		x>>=1;
	}
	return dfs(len-1,32,1,1);
}
int main()
{
	ll n,m;
	cin>>n>>m;
	memset(dp,-1,sizeof(dp));
	cout<<solve(m)-solve(n-1)<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/why932346109/article/details/86653183