hdu3652 B-number 数位dp

来源:互联网 发布:七天网络登录阅卷 编辑:程序博客网 时间:2024/05/20 05:54

B-number

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4376 Accepted Submission(s): 2520

Problem Description
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
13
100
200
1000

Sample Output
1
1
2
2

和以前的数位dp的模板是一样的,只是怎么表示能被13整除?我们可以用余数来表示状态。

#include<bits/stdc++.h>using namespace std;int dp[15][3][13];int digit[20];int f(int n) {    int len=0;    while(n) {        digit[len++]=n%10;        n/=10;    }    digit[len]=0;    return len-1;}/**25 13 ==12120+4%13==117 7254 13 ==7*/int dfs(int pos,int sta,int mod,int lim) {    if(pos<0)return sta==2&&mod==0;    if(!lim&&dp[pos][sta][mod]^-1)return dp[pos][sta][mod];    int len=lim?digit[pos]:9;    int ans=0;    for(int i=0; i<=len; ++i) {        int ts=sta;        if(ts==0&&i==1)ts=1;        else if(ts==1&&i==3)ts=2;        else if(ts==1&&(i!=1&&i!=3))ts=0;        ans+=dfs(pos-1,ts,(mod*10+i)%13,lim&&(i==len));    }    return lim?ans:(dp[pos][sta][mod]=ans);}int main() {    int n;    memset(dp,-1,sizeof(dp));    while(~scanf("%d",&n)) {        printf("%d\n",dfs(f(n),0,0,1));    }    return 0;}
0 0