当前位置 : 主页 > 编程语言 > c语言 >

HDU 4734 F(x) 数位dp

来源:互联网 收集:自由互联 发布时间:2023-09-03
HDU 4734 F(x) Time Limit: 1000/500 MS (Java/Others)Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 6341Accepted Submission(s): 2438 Problem Description For a decimal number x with n digits (A n A n-1 A n-2 ... A 2 A 1 ), we d


HDU 4734

F(x)

Time Limit: 1000/500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6341    Accepted Submission(s): 2438


Problem Description


For a decimal number x with n digits (AnAn-1An-2 ... A2A1), we define its weight as F(x) = An * 2n-1 + An-1 * 2n-2 + ... + A2 * 2 + A1 * 1. Now you are given two numbers A and B, please calculate how many numbers are there between 0 and B, inclusive, whose weight is no more than F(A).


 




Input


The first line has a number T (T <= 10000) , indicating the number of test cases.
For each test case, there are two numbers A and B (0 <= A,B < 109)


 




Output


For every case,you should output "Case #t: " at first, without quotes. The t is the case number starting from 1. Then output the answer.


 




Sample Input


3 0 100 1 10 5 100


 




Sample Output


Case #1: 1 Case #2: 2 Case #3: 13


 




Source


2013 ACM/ICPC Asia Regional Chengdu Online


 




Recommend


liuyiding   |   We have carefully selected several similar problems for you:  6193 6192 6191 6190 6189 


【解析】:

关于数位dp详细的题解在 hdu2089的题解里:javascript:void(0)

本篇是我做的第二个数位dp练习题。


这题有个坑一直卡着我。dfs的第二个参数sum。本题限制不超过f(A)。令upnum=f(A),

那我就可以用它来限制着dfs的递归,当递归过程的sum>upnum,就return,可是死活不能AC

然后看着网上的代码,改成给这个参数赋初值为upnum,然后递归时去减,减到<0就return,没想到就AC了。

大概是跟dp数组的记忆化有关。

【代码】:


#include <stdio.h>
#include <string.h>  
#define mset(a,i) memset(a,i,sizeof(a))
int dp[26][15240];//dp[i][sum]表示第i位,和sum时的记忆。
int a[26];
int upnum;
int dfs(int pos,int sum,bool limit)
{
	if(sum<0)return 0;
	if(pos==-1)return sum>=0;
	if(!limit&&dp[pos][sum]!=-1)return dp[pos][sum];
	int up=limit?a[pos]:9;
	int ans=0;
	for(int i=0;i<=up;i++)
	{
		ans+=dfs(pos-1,sum-i*(1<<pos),limit&&i==up);
	}
	if(!limit)dp[pos][sum]=ans;
	return ans;
}
int solve(int x)
{
	int top=0;
	while(x)
	{
		a[top++]=x%10;
		x/=10;
	}
	return dfs(top-1,upnum,1);
}
int f(int A)
{
	int ans=0;
	for(int j=0;A;j++,A/=10)
		ans+=(1<<j)*(A%10);
	return ans;
}
int main()
{
	int T,A,B,r=1;
	scanf("%d",&T);
	memset(dp,-1,sizeof(dp));
	while(T--)
	{
		scanf("%d%d",&A,&B);
		upnum=f(A);
		printf("Case #%d: %d\n",r++,solve(B));
	}
	return 0;
}




网友评论