POJ3252 Round Numbers

来源:互联网 发布:交大网络教育学院分校 编辑:程序博客网 时间:2024/06/10 18:10

Round Numbers
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 14198 Accepted: 5663

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

Source

USACO 2006 November Silver

——————————————————————————————————————

题目的意思是求一段区间里化成2进制后0和1的数量相同的数有几个

思路:数位dp,3位数组表示到len位为止,0有cnt0个1有cnt1个的书有多少个,dfs求解,注意前导零

#include <iostream>#include <cstring>#include <string>#include <vector>#include <queue>#include <cstdio>#include <set>#include <cmath>#include <map>#include <algorithm>#define INF 0x3f3f3f3f#define MAXN 10000005#define Mod 10001using namespace std;#define LL long longLL dp[100][100][100];int a[100];LL dfs(int len,int cnt0,int cnt1,bool limit,int zero){    if(len<0)        return cnt0>=cnt1;    if(dp[len][cnt0][cnt1]!=-1&&!limit)        return dp[len][cnt0][cnt1];    int up=limit?a[len]:1;    LL ans=0;    for(int i=0; i<=up; i++)    {        if(i==0)        ans+=dfs(len-1,zero?cnt0:cnt0+1,cnt1,limit&&i==up,zero);        else        ans+=dfs(len-1,cnt0,cnt1+1,limit&&i==up,0);    }    return limit?ans:dp[len][cnt0][cnt1]=ans;}LL solve(LL x){    int cnt=0;    while(x>0)    {        a[cnt++]=x%2;        x/=2;    }    return dfs(cnt-1,0,0,1,1);}int main(){    LL n,m;    memset(dp,-1,sizeof dp);    while(~scanf("%lld%lld",&m,&n))    {        printf("%lld\n",solve(n)-solve(m-1));    }    return 0;}





原创粉丝点击