您的位置:首页 > 其它

POJ 3252 Round Numbers (数位dp)

2017-04-24 19:16 393 查看

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入门题。写成dfs比较方便。

注意前导零对答案的影响。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
using namespace std;

int a[35], dp[35][70];
int L, R;

int dfs(int pos, int sta, bool lead, bool limit){
if(pos == 0)  return sta >= 32;//注意=也可
if(!lead && !limit && ~dp[pos][sta])  return dp[pos][sta];//注意记忆化的条件
int up = limit ? a[pos] : 1, ans = 0;//高位限制

for(int i = 0; i <= up; i++){
if(lead && !i)  ans += dfs(pos-1, sta, true, limit && i == a[pos]);//注意前导零对状态不产生贡献
else  ans += dfs(pos-1, sta + (i == 0 ? 1 : -1), false, limit && i == a[pos]);//dfs处理子问题
}
if(!lead && !limit)  dp[pos][sta] = ans;//记忆化
return ans;
}

int Sol(int num){
int pos = 0;

while(num){
a[++pos] = num & 1;
num >>= 1;
}//分解
return dfs(pos, 32, true, true);//0->32(简单的hash)
}

int main(){

memset(dp, -1, sizeof(dp));//初始化

scanf("%d%d", &L, &R);

printf("%d\n", Sol(R) - Sol(L - 1));

return 0;
}


哪有什么伤心事,一定是你不读书还想太多。——杨绛
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: