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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值