http://acm.hdu.edu.cn/showproblem.php?pid=4734
Problem Description
For a decimal number x with n digits (A
nA
n-1A
n-2 ... A
2A
1), we define its weight as F(x) = A
n * 2
n-1 + A
n-1 * 2
n-2 + ... + A
2 * 2 + A
1 * 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 < 10 9)
For each test case, there are two numbers A and B (0 <= A,B < 10 9)
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
/**
hdu 4734 数位dp 记忆化搜索
题目大意:求给定区间1~B中所有小于f(A)的数。
解题思路:记忆化搜索, 标记dp[i][j]表示i位数比j小的数的个数。时间卡的很紧,不用记忆化会超时的
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
int A,B,dp[11][50000],a[25];
int len;
int f(int n)
{
int ans=0,len=1;
while(n)
{
ans+=n%10*len;
len*=2;
n/=10;
}
/// printf("f(a)=%d\n",ans);
return ans;
}
int dfs(int len,int ans,int flag)
{
if(len<0) return ans>=0;
if(ans<0) return 0;
int sum=0;
if(!flag&&dp[len][ans]!=-1)return dp[len][ans];
int end=flag?a[len]:9;
for(int i=0; i<=end; i++)
{
sum+=dfs(len-1,ans-i*(1<<len),flag&&i==end);
}
if(!flag)dp[len][ans]=sum;
return sum;
}
int main()
{
int T,tt=0;
scanf("%d",&T);
memset(dp,-1,sizeof(dp));
while(T--)
{
scanf("%d%d",&A,&B);
len=0;
while(B)
{
a[len++]=B%10;
/// printf("%d ",a[len-1]);
B/=10;
}
///printf("\n");
printf("Case #%d: %d\n",++tt,dfs(len-1,f(A),1));
}
return 0;
}