HDU 3652 B-number 数位dp+记忆化搜索

来源:互联网 发布:vb与台达plc通讯 编辑:程序博客网 时间:2024/06/16 22:37
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.
Input
Process till EOF. In each line, there is one positive integer n(1 <= n <= 1000000000).
Output
Print each answer in a single line.
Sample Input
131002001000
Sample Output
1122
基础数位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;}


原创粉丝点击