本文主要是介绍数位DP | 组合数学 —— POJ 3252,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
对应POJ题目:点击打开链接
Round Numbers
Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u Submit Status Practice POJ 3252
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).
Output
Line 1: A single integer that is the count of round numbers in the inclusive range Start.. Finish
题意:
求区间[a, b]内有多少个数的二进制中0的数量不小于1的数量。
思路:
从高位开始枚举二进制数,dp[cnt][n0][n1]表示在cnt位数(二进制下)时0的数量为n0,1的数量为n1时有多少个满足题意的解,递归进行记忆化搜索求出[0, a] 内的解和[0, b]内的解,则ans = solve(b) - solve(a - 1)。
也可使用组合数学完成。
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
const int INF=1<<30;
const int MAXN=100000+10;
int num[35];
int dp[35][35][35];int dfs(int len, int n0, int n1, bool e)
{if( !e && dp[len][n0][n1] !=-1 ) return dp[len][n0][n1];if(len==0){if(n0>=n1) return 1;return 0;}int ans=0;int u=e?num[len]:1; //如果当前位有限制,则u不能超过限定值(0或1),否则没限制(即u取1)for(int i=0; i<=u; i++){ans+=dfs(len-1, n0+(i==0&&n1!=0), n1+(i!=0), (i==u)&&e);//如果当前位的值为0且之前出现过1(如果当前位之前全为0,则相当于前导0),则0的数量+1,否则1的数量+1//如果当前位有限制且已经枚举到限定值,则下一位有限制}if(!e) dp[len][n0][n1] =ans;return ans;
}int solve(int x)
{int cnt=0;while(x){num[++cnt]=x&1;x>>=1;}return dfs(cnt,0,0,1);
}int main()
{//freopen("in.txt","r",stdin);int n,m;while(scanf("%d%d", &n,&m)==2){memset(dp,-1,sizeof(dp));printf("%d\n", solve(m)-solve(n-1));}return 0;
}
这篇关于数位DP | 组合数学 —— POJ 3252的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!