HUD 3652 B-number(三维数组维护:最高位限制 取模后的余数 是否存在13)

题目链接:https://vjudge.net/contest/396083#problem/D

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

翻译:
给定一个n,求1~n中有多少个符合条件的数
条件:这个数能被13整除,还包含13

分析:

如何判断这个数能被13整除,还包括13是重点

1.能被13整除?
对于每一位累加还原成原数的过程中直接取模

2.包括13?
k=0时:前i位没有13
k=1时:第i位位1
k=2时:前i位出现了13

随之而来的是三维数组:

dp[i][sta][k]:

完整代码:

#include<cstdio>
#include<cstring>
#include<math.h>
#include<stdlib.h>
#include<queue>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
LL n;
int a[30];
int dp[30][20][4];///dp[i][j][k]:前i位对13取模的结果是j,k=0前i位没有13,k=1前i位只有一个1,k=2前i位有13
LL dfs(int pos,int sta,int k,int limt)
{
    if(pos==0)
        return sta==0&&k==2;///保证余数为0,且出现过13
    if(!limt&&dp[pos][sta][k]!=-1)
        return dp[pos][sta][k];
    int up=limt?a[pos]:9;
    LL res=0;
    for(int i=0; i<=up; i++)
    {
        int mod=(sta*10+i)%13;
        if(k==1&&i==3||k==2)
            res+=dfs(pos-1,mod,2,limt&&(i==up));
        else if(i==1)
            res+=dfs(pos-1,mod,1,limt&&(i==up));
        else
            res+=dfs(pos-1,mod,0,limt&&(i==up));
    }
    if(!limt)
        dp[pos][sta][k]=res;
    return res;
}
LL solve(LL x)
{
    int tot=0;
    while(x)
    {
        a[++tot]=x%10;
        x/=10;
    }
    return dfs(tot,0,0,1);
}
int main()
{
    memset(dp,-1,sizeof(dp));
    while(~scanf("%lld",&n))
    {
        printf("%lld\n",solve(n));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zaiyang遇见

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值