F(x)
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5003 Accepted Submission(s): 1864
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)
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
Source
Recommend
//初始的是时候sum是f(a),枚举一位就减去这一位在计算f(i)的权值,显然sum=0时就是满足的,后面的位数凑足sum位就可以了 //只有sum==0时,满足条件 #include<cstdio> #include<cstring> using namespace std; const int N=1e4+5; int cas,A,b,a[12],dp[12][N],all; int f(int x){ if(!x) return 0; return (f(x/10)<<1)+(x%10); } int dfs(int pos,int sum,bool limit){ if(!pos) return sum<=all; if(sum>all) return 0; if(!limit && dp[pos][all-sum]!=-1) return dp[pos][all-sum]; int up=limit?a[pos]:9; int ans=0; for(int i=0;i<=up;i++){ ans+=dfs(pos-1,sum+i*(1<<pos-1),limit && i==a[pos]); } if(!limit) dp[pos][all-sum]=ans; return ans; } int solve(int x){ int pos=0; for(;x;x/=10) a[++pos]=x%10; return dfs(pos,0,1); } int main(){ memset(dp,-1,sizeof dp); scanf("%d",&cas); for(int i=1;i<=cas;i++){ scanf("%d%d",&A,&b); all=f(A); printf("Case #%d: %d ",i,solve(b)); } return 0; }