Round Numbers
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
解题思路:
数位DP。
dp[pos][sta]表示枚举到pos位时,0的个数减去1的个数不小于sta时的值。
那么sta可正可负。最小也就是-32,那么可以给他们全部加上32。
那么sta表示的状态就从-32 ~ 32 变成了0-64。
所以一开始的时候就是32,即 0 的状态,当枚举到最后一位时。同样也是通过判断sta >= 32 来判断合法性。
不是很懂这里:
这题的前导0对于枚举的状态也是有影响的。若前一位数位0时,而该位也为0。
那么sta 的值不变化。否则若当前位为0,则 sta++,否则sta–。
例如: 1100
在枚举第一位的时候为1,此时sta = 31;
在枚举第二位的时候为1,此时sta = 30;
在枚举第三位的时候为0,此时sta = 31;
在枚举第四位的时候为0,此时sta = 31。
参考:
https://blog.csdn.net/wust_zzwh/article/details/52100392
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1e6+10;
int dp[66][100];
int num[66];
int dfs(int pos,int sta,int lead,int limit)
{
if(pos == -1) return sta >= 32;
if(!lead && !limit && dp[pos][sta]!= -1) return dp[pos][sta];
int up = limit ? num[pos] : 1;
int tmp = 0;
for(int i = 0 ;i <= up ; i ++)
{
if(lead && i == 0) tmp += dfs(pos-1,sta,lead,limit && num[pos] == i);
else tmp += dfs(pos-1,sta+(i == 0 ? 1 : -1),0,limit && num[pos] == i);
}
if(!lead && !limit ) dp[pos][sta] = tmp;
return tmp;
}
int res(int a)
{
int pos = 0;
while(a)
{
num[pos ++] = a&1;
a >>= 1;
}
return dfs(pos-1,32,1,1);
}
int main()
{
int a,b;
memset(dp,-1,sizeof(dp));
while(cin>>a>>b)
{
cout<<res(b)-res(a-1)<<endl;
}
return 0;
}