A wqb-number, or B-number for short, is a non-negative integer whose decimal form contains the sub- string "13" and can be divided by 13. For example, 130 and 2613 are wqb-numbers, but 143 and 2639 are not. Your task is to calculate how many wqb-numbers from 1 to n for a given integer n.
13 100 200 1000
1 1 2 2
基础数位dp和记忆化搜索 直接套模板;
代码如下:
#include<stdio.h> #include<cstring> int dp[20][20][3]; int a[20]; int dfs(int pos,int pre,int sta,bool limit) { if(pos <= 0) return pre==0 && sta==2; if(!limit && dp[pos][pre][sta]!=-1) return dp[pos][pre][sta]; int up=limit?a[pos]:9; int tmp = 0; int x , y; for(int i = 0; i <= up; i++) { x = (pre*10+i)%13; y = sta; if(sta==0 && i==1) y = 1; if(sta==1 && i!=1) y = 0; if(sta==1 && i==3) y = 2; tmp+=dfs(pos-1,x,y,limit && i==up); } if(!limit) dp[pos][pre][sta] = tmp; return tmp; } int solve(int x) { int t = 0; while(x) { a[++t] = x%10; x /= 10; } return dfs(t,0,0,1); } int main() { int n; while(~scanf("%d",&n)&&n) { memset(dp,-1,sizeof(dp)); memset(a,0,sizeof(a)); printf("%d\n",solve(n)); } return 0; }