hdu 3652(数位dp)

来源:互联网 发布:网页版淘宝网 电脑版 编辑:程序博客网 时间:2024/06/06 14:18

传送门
题解:求1~n中出现过”13”且mod 13为0的数的个数。
数位dp模板题,具体注释看代码。
注意:记忆化搜索只能记当前数位没有限制的dp值。

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;int n,dp[10][13][2][10],b[10];int dfs(int pos,int mod,int t,int now,bool lim) {    //当前数位,当前mod 13的值,当前是否出现13,当前位的数,这一位枚举是否有上限    if (pos==-1) return !mod&&t;    if (!lim&&~dp[pos][mod][t][now]) return dp[pos][mod][t][now];    int end=lim?b[pos]:9,ans=0;    for (int i=0;i<=end;++i)        ans+=dfs(pos-1,(mod*10+i)%13,t||(now==1&&i==3),i,lim&&i==end);    if (!lim) dp[pos][mod][t][now]=ans;    return ans;}inline int work(int x) {    int len=0;    while (x) {        b[len++]=x%10;        x/=10;    }    return dfs(len-1,0,0,0,1);}int main() {    memset(dp,-1,sizeof(dp));    while (~scanf("%d",&n)) {        printf("%d\n",work(n));    }    return 0;}
原创粉丝点击