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
数位dp总有一种模板题的感觉,改几个参数就可以= =
因为之前做过统计前几位之和的题目,所以很自然的就想还是这么做,到最后只要返回presum<=F(A) 就可以了,
但是这道题目这样做存在一个问题,对于组不同的输入,F(A)都是不同的,这就意味着我们要在每组输入的时候将dp数组重新初始化,重新计算每个位置的值。
于是这样就华丽丽的T了。
一般来说数位dp中的初始化只要一次,放在最外面就可以,所以我们就不能在判断的时候使用这个一直在变化的F(A),那么其实我们只要dp数组中的第二维不要存之前的和,而是存当前值与预期F(A)的差值即可,最后只要判断k>=0。
还要注意因为存的是差值,可能会出现负数,要进行判断提前退出,否则可能访问越界。
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
#define ll long long
#define CL(a) memset(a,0,sizeof(a))
#define maxn 150010
#define mod 2520
int dp[25][15000];
int num[25];
int res;
int fun(int x)
{
int ans=0;
int i=1;
while(x)
{
ans+=(x%10)*i;
i*=2;
x/=10;
}
return ans;
}
int dfs(int pos,int k,bool limit)
{
if(pos==-1) return k>=0;
if(k<0) return 0; //这句话一定要加! 否则下面可能会数组越界,导致WA
if(!limit&&dp[pos][k]!=-1)
return dp[pos][k];
int ed=limit?num[pos]:9;
int ans=0;
for(int i=0; i<=ed; i++)
{
ans+=dfs(pos-1,k-i*(1<<pos),limit&&i==ed);
}
return limit?ans:dp[pos][k]=ans;
}
int cal(int p)
{
int len=0;
while(p)
{
num[len++]=p%10;
p/=10;
}
return dfs(len-1,res,1);
}
int main ()
{
int t,cas=0;
int a,b;
cin>>t;
memset(dp,-1,sizeof(dp));
while(t--)
{
cin>>a>>b;
res=fun(a);
printf("Case #%d: ",++cas);
cout<<cal(b)<<endl;
}
return 0;
}