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)
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
memset放外层条件每个数只与本身有关,与输入无关,这个题如果用当前的和sum做状态,最终结果sum<=f(a)依赖于输入,只能把memset放里层,会超时,而转化成F(a)-sum最终大于等于0即可,不依赖于输出,可以放外层,这样降低时间复杂度
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
ll dp[50][5000];
int bit[50];
int t;
ll a,b;
ll init(ll x)
{
ll ans=0;
int p=1;
while(x)
{
ans+=(x%10)*p;
x/=10;
p<<=1;
}
return ans;
}
ll dfs(int pos,int sum,int limit)
{if(sum<0)
return 0;
if(pos==-1)
return sum>=0;
if(!limit&&dp[pos][sum]!=-1)
return dp[pos][sum];
ll ans=0;
int up=limit?bit[pos]:9;
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;
}
ll solve(ll x)
{int pos=0;
while(x)
{
bit[pos++]=x%10;
x/=10;
}
return dfs(pos-1,init(a),1);
}
int main()
{scanf("%d",&t);
memset(dp,-1,sizeof(dp));
int w=0;
while(t--)
{
w++;
scanf("%lld%lld",&a,&b);
printf("Case #%d: %lld\n",w,solve(b));
}
return 0;
}