F(x)
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 6560 Accepted Submission(s): 2532
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题意: 给你数a和b 你要做的是求出在0到b的闭区间中有多少数是f(x)小于等于f(a)的。思路: 暴力肯定是不可以的,所以想到用数位dp 虽说是个模板题,但是对于我还是思考了好长时间,主要是没怎么写过数位dp dp【pos】【num】表示i位数以内中小于等于num的数,这里有两个边界条件,第一个是当pos==0的时候,这时候我们可以注意到 只要num>=0 那么就可以返回1 第二个边界是num<0 , 显然是返回 0接下来最重要的是dp方程的建立 ,,dp[pos][num]+=dp[pos-1][num-i(2的pos-1次方)];这里稍微难理解一点的是为什么num-i*(2的pos-1次方) ,当pos位满足的<num 的时候,很显然是第pos-1 位满足num-i*(pos-1)。代码:#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> using namespace std; typedef long long ll; int dp[20][9300]; int aa[20]; int f(int x) { int len=0; int ans=1; int f=0; while(x) { f+=(x%10)*ans; ans*=2; x/=10; } return f; } int ff(int x) { int len=0; while(x) { aa[++len]=x%10; x/=10; } return len; } int dfs(int pos,int num,int f) { //printf("%d %d %d \n",pos,num,f); if(pos==0) return num>=0; if(num<0) return 0; if(!f&&dp[pos][num]!=-1) return dp[pos][num]; int ans=0; int end; end=f?aa[pos]:9; for(int i=0;i<=end;i++) { ans+=dfs(pos-1,num-i*(1<<(pos-1)),f&&(i==end)); } if(!f) dp[pos][num]=ans; return ans; } int main() { int cas; int a,b; scanf("%d",&cas); int kk=0; memset(dp,-1,sizeof(dp)); while(cas--) { scanf("%d %d",&a,&b); printf("Case #%d: %d\n",++kk,dfs(ff(b),f(a),1)); /* for(int i=0;i<=3;i++) { for(int j=1;j<=5;j++) printf("%d ",dp[i][j]); printf("\n"); }*/ } return 0; }