POJ - 3252 E - Round Numbers (数位dp)

https://cn.vjudge.net/problem/POJ-3252    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

题意:每个数字都有一个对应的二进制10010101,二进制中0的个数比1的个数多那么就称这个数字为”round numbers”。

求 [ L , R ] 区间中有多少个”round numbers”数字。

思路:数位dp,

int dp[pos][num0][num1]; pos表示位数,sta代表pos位之前(不含第pos位)是否有1出现过,(因为前导0是不能计算的),num0表示出现了几个0(1出现之后,num0才能++,防止前导0出现),num1表示1出现的个数

#include <iostream>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <queue>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
typedef long long LL;
const LL mod=1e9+7;
const int M=13;
using namespace std;
const int N =1e5+100;
int dp[40][40][40];//dp[pos][num0][num1];
int a[40];
int dfs(int pos,int sta,int num0,int num1,int limit)//未注释的都是数位dp板子,不再解释
{
    if(pos==-1) return num0>=num1&&num1>=1;//0的个数大于1的个数,并且有1出现
    if(!limit&&~dp[pos][num0][num1]) return dp[pos][num0][num1];
    int up=limit? a[pos]:1,ans=0;
    for(int i=0;i<=up;i++)
        ans+=dfs(pos-1,sta||(i==1),sta?num0+(i==0):num0,num1+(i==1),limit&&i==up);
    //(若1出现过那么sta=1)(若sta==1(1出现过),若i==0,则num0++)(若i==1,则num1++)
    return limit? ans:dp[pos][num0][num1]=ans;
}
int slove(int x)//转化为2进制
{
    int pos=0;
    while(x)
    {
        a[pos++]=x%2;
        x/=2;
    }
    return dfs(pos-1,0,0,0,1);
}
int main()
{
    mem(dp,-1);
    int a,b;
    scanf("%d%d",&a,&b);
    printf("%d\n",slove(b)-slove(a-1));
}



猜你喜欢

转载自blog.csdn.net/xiangaccepted/article/details/80507303