B-number HDU - 3652 (数位dp 13数)

本文介绍了一种特殊的整数——WQB数,这类数的十进制形式中包含子字符串'13'且能被13整除。文章提供了一个算法,用于计算从1到给定整数n范围内所有符合条件的WQB数的数量。
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


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <map>
#include <vector>
using namespace std;
int bit[20];
int dp[20][13][3];//    位数,  前一位的mod13的余数, 状态
// 状态0表示 尾数数不是 1   状态1表示 尾数为1   状态2表示   包含13
int dfs(int pos, int mod, int state, bool limit) {
    if (pos == -1)
        return mod == 0 && state == 2;
    if (!limit && dp[pos][mod][state] != -1)
        return dp[pos][mod][state];
    int up = limit ? bit[pos] : 9;
    int temp = 0;
    for (int i = 0; i <= up; ++i) {
        int mod_n = (mod*10 + i) % 13;
        int have = state;           //如果state == 2,则状态不需要改变
        if (state == 0 && i == 1)   //上一位非1,这一位为1,改变状态
            have = 1;
        if (state == 1 && i != 1)   //上一位为1,这一位非1,改变状态
            have = 0;
        if (state == 1 && i == 3)   //上一位为1,这一位为3,令状态state = 2;
            have = 2;
        temp += dfs(pos-1, mod_n, have, limit && i == bit[pos]);
    }
    
    if (!limit)
        dp[pos][mod][state] = temp;
    return temp;
}
int solve(long long x) {
    int i = 0;
    while (x) {
        bit[i++] = x%10;
        x /= 10;
    }
    return dfs(i-1, 0, 0, 1);
}

int main() {
    long long n;
    while (cin >>n) {
        memset(dp, -1, sizeof(dp));
        cout << solve(n) << endl;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值