B-number
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 求1到n中含有13且能够被13整除的数有多少个…… 跟之前的题略有不同,加了一能够整除13的条件!!! 于是状态就多了一个当前数除以13的余数,其他的都和前两题差不多,完美解决!
#include <iostream>
#include <string>
#include <stdio.h>
#include <cstring>
using namespace std;
int bit[40];
int f[40][20][4];
int dp(int pos, int mod, int st, int flag)
{
if (pos == 0) return (st == 2 && mod == 0);
if (flag && f[pos][mod][st] != -1) return f[pos][mod][st];
int ans = 0;
int x = flag ? 9 : bit[pos];
for (int i = 0; i <= x; i++)
{
int tmp = (mod * 10 + i) % 13;
if ((st == 2) || (st == 1 && i == 3))
ans += dp(pos - 1, tmp, 2, flag || i < x);
else if (i == 1) ans += dp(pos - 1, tmp, 1, flag || i <x);
else ans += dp(pos - 1, tmp, 0, flag || i < x);
}
if (flag) f[pos][mod][st] = ans;
return ans;
}
int calc(int x)
{
int len = 0;
while (x)
{
bit[++len] = x % 10;
x = x / 10;
}
dp(len, 0, 0, 0);
}
int main()
{
int n;
memset(f, -1, sizeof(f));
while (scanf("%d", &n) != EOF)
{
printf("%d\n", calc(n));
}
return 0;
}