B-number HDU - 3652 (数位DP)

题目描述:

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.

题意:问你在 1 ~ n 的所有数中 含有13 或者 可以被 13 整除的数有多少。

解题思路:这是一道数位dp题,用 dp[ len] [ mod ] [ if1] [sta ] 表示状态,其中len表示此时访问的位数,mod用来确定该数是否可以整除13,if1 表示其前缀是否有1,用来判断是否含13 ,sta用来表示该数此时的状态。然后再套用数位dp的模板即可。

代码:

#include<bits/stdc++.h>
#define ll long long
#define MOD 998244353 
#define INF 0x3f3f3f3f
#define mem(a,x) memset(a,x,sizeof(a))  
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;



//含13 或可以被13整除的数
ll dp[20][20][2][2];
ll digit[20];
ll dfs(int len,int mod,int if1,int sta,int ismax)
{
    ll ans=0,maxx;
    if(!len)return (mod%13==0)&&(sta==1);   //表示这个数既被13整除 又含有13,为防止重复
    if(!ismax&&dp[len][mod][if1][sta]!=-1)return dp[len][mod][if1][sta];
    maxx= (ismax?digit[len]:9);
    for(int i=0;i<=maxx;i++){
        int temp=(mod*10+i)%13;   //判断是否被13整除
        if(i==1){
            ans+=dfs(len-1,temp,1,sta,ismax&&i==maxx);   //前缀为1
        }else if(i==3&&if1){
            ans+=dfs(len-1,temp,0,1,ismax&&i==maxx);    //含有13
        }else{
            ans+=dfs(len-1,temp,0,sta,ismax&&i==maxx);
        }
    }
    if(!ismax)dp[len][mod][if1][sta]=ans;
    return ans;
}
ll solve(ll n)
{
    mem(digit,0);
    int len=0;
    while(n){
       digit[++len]=n%10;
       n/=10;
    }
    return dfs(len,0,0,0,1);
}
int main()
{
    ll n,t;
    while(~scanf("%lld",&n)){
        mem(dp,-1);
        printf("%lld\n",solve(n));
    }
    return 0;
}

 

posted @ 2020-07-29 00:41  hachuochuo  阅读(63)  评论(0编辑  收藏  举报