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).
题意:给出对于数字x, f(x)的计算方法,问一个区间[0, B]内有多少个数字的f(i)值是不大于f(A)的
数位dp的思路很简单,用dp[pos][sum]表示状态,由于每一次询问的结果与输入f(A)有关,所以直接计算sum是不能记忆化的,必须每次询问去memset,这样子就会超出时间限制。如果在dp状态上记录一个f(A),这样空间也会受到限制。 所以在计算sum的时候,我们表示后面还差多少值,也就是给sum一个初始的F(A),然后去减每一位的权值。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL a;
LL dp[20][5555];
int dig[15];
int z[15];
LL dfs(int pos, int sum, int limit)
{
if(pos < 1) return sum >= 0;
if(sum < 0) return 0;
if(!limit && dp[pos][sum] != -1)
return dp[pos][sum];
int n = limit ? dig[pos] : 9;
LL res = 0;
for(int i = 0; i <= n; ++i)
{
res += dfs(pos-1, sum-z[pos]*i, limit&&i==n);
}
if(!limit) dp[pos][sum] = res;
return res;
}
LL f(LL a)
{
int F = 0;
int len = 1;
while(a)
{
F += len*(a%10);
a /= 10;
len *= 2;
}
return F;
}
LL call(LL x)
{
int len = 0;
while(x)
{
dig[++len] = x%10;
x /= 10;
}
return dfs(len, f(a), 1);
}
int main()
{
ios::sync_with_stdio(false);
memset(dp, -1, sizeof(dp));
z[1] = 1;
for(int i = 2; i < 15; ++i)
z[i] = z[i-1]*2;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif // ONLION_JUDGE
int Case = 1;
int T;
cin >> T;
while(T--)
{
LL b;
cin >> a >> b;
cout << "Case #" << Case++ << ": " << call(b) << endl;
}
return 0;
}