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
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
题意:给个区间,输出对应范围内十进制的二进表达中0的数量大于等于1的数量的数的个数 |
思路(数位dp):
·和普通数位dp同样的做法,十进制的数位表达同样适用于二进制,只是把上限最大改为了1,最小仍是0,依照题意,我们可以设置状态数sta,比如初始化为0,然后遇到0就对状态数贡献+1,否则(为1)就对其-1,如果最后状态数sta>=0就说明0的个数大于等于1的个数。
·所以可以用dp[pos][sta]表示在pos位置往时,状态数等于sta时满足题意的数的个数。因为sta不能为负,所以可以设初始值为一个较大的常数,然后对比最后的sta>=add是否成立即可
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <map>
#include <algorithm>
#define maxn 10000+500
using namespace std;
typedef long long ll;
ll dp[60][150]; //dp[pos][sta] 代表pos位置往后满足状态量大于等于sta的数的个数
ll a[60];
ll add=50;
ll dfs(int pos, int sta,bool lead, bool limit) //sta表示状态增量,初始为add
{
if(pos==-1) return sta >= add; //如果当前状态不满足 sta>=add返回0,满足则返回贡献度1
if(!lead&&!limit&&dp[pos][sta]!=-1) return dp[pos][sta]; //记忆化搜索
ll up = limit?a[pos]:1; //01串, 前面有限制条件则当前位上限为自身, 如 110 在前两位固定是1的情况下第三位只能是0不能是1
ll ans = 0;
for(ll i=0;i<=up;i++)
{
if(i==0&&lead) ans += dfs(pos-1,sta, true, limit&&a[pos]==i ); //有前导零且当前为也作前导零,不计入sta,继续往下
else ans += dfs(pos-1,sta+(i==1?-1:1), false, limit&&a[pos]==i); //否则就是正常二进制序列, 0 对状态贡献1, 1则贡献-1,最后对比增量改变量和add就知道01数量对比
}
if(!limit&&!lead) dp[pos][sta] = ans; //没有限制条件就记忆化
return ans;
}
ll solve(ll x)
{
int pos=0;
while(x)
{
a[pos++]=x&1;
x>>=1;
}
return dfs(pos-1,add,true,true);
}
int main()
{
memset(dp,-1,sizeof dp);
ll a,b;
while(~scanf("%lld%lld",&a,&b))
{
printf("%lld\n",solve(b)-solve(a-1));
}
return 0;
}