题意:找出i在0到b之间的f(i)小于等于f(a)的数的个数。
思路:数位dp。主要在于状态转移不好想。dp[i][j]表示i位数比j小的数的个数。用递归完成的话就只需要思考边界和状态转移。
边界:
dp[i][j]如果j小于0,显然是dp[i][j]=0的,如果i==0,说明就是0,显然任何数都比0大,所以dp[i][j]对于j>=0的时候dp[i][j]=1,否则dp[i][j]=0。
状态转移:
dp[i][j]+=dp[i-1][j-k*(1<<(i))];j的初始值是sum
完成上述两步推导就能开始写这题了。
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int MOD = 1000000007; const int maxn = 200010; int num[30],len; LL dp[30][10000]; int a[50]; int sum; LL dfs(int pos,LL zhi,int last)//zhi是差值 { if(pos<0) return zhi>=0;//当差值大于等于0时,说明这个数符合要求,+1,否则+0 if(zhi<0) return 0;//当差值小于0时就+0, if(!last&&dp[pos][zhi]!=-1) { return dp[pos][zhi]; } int len=last?num[pos]:9; LL res = 0; for(int i=0; i<=len; i++) { res += dfs(pos-1,(zhi-i*(1<<pos)),last&&(i==len)); } if(!last)dp[pos][zhi]= res; return res; } LL solve(LL n) { len = 0; while(n) { num[len++] = n; n /= 10; } return dfs(len-1,sum,1);//用sum一直去减 } int main() { memset(dp,-1,sizeof(dp)); int _; scanf("%d",&_); int g=0; while(_--) { LL n,m; ++g; scanf("%I64d%I64d",&m,&n); sum=0; int l=0; while(m)//算sum { sum+=(m)*(1<<l); l++; m=m/10; } printf("Case #%d: ",g); if(sum==0) printf("%d\n",1); else printf("%I64d\n",solve(n)); } return 0; }