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
思路:状态dp[i][j]表示位数为i的数中不大于j的数有多少;状态转移方程dp[i][j]=sum{dp[i-1][j-k*(1<<i-1)]}(k<=limit?digit[i]:9)
AC代码:
#include <iostream> #include<cstdio> typedef long long ll; using namespace std; ll dp[15][30100]; ll digit[15]; ll dfs(ll len,ll ans,bool limit){ if(len==0) return 1; if(!limit && dp[len][ans]) return dp[len][ans]; ll sum=0; for(ll i=0;i<=(limit?digit[len]:9);i++){ if(i*(1<<(len-1))<=ans) sum+=dfs(len-1,ans-i*(1<<(len-1)),limit&&i==digit[len]); } if(!limit) dp[len][ans]=sum; return sum; } ll solve(ll x,ll a){ digit[0]=0; while(x){ digit[++digit[0]]=x%10; x/=10; } ll tot=0,tmp=1; while(a) tot+=a%10*tmp,a/=10,tmp*=2; return dfs(digit[0],tot,true); } int main() { ll t;scanf("%lld",&t); for(ll k=1;k<=t;k++){ ll a,b;scanf("%lld%lld",&a,&b); printf("Case #%lld: %lld\n",k,solve(b,a)); } return 0; }