B-number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
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
————————————————————集训18.2的分割线————————————————————
前言:有电脑上不上网,重启路由器却把Roll神的网顶掉了。。把Roll神气得回家了。。Sorry and Sad
思路:和不要62那道题有一定的相似度。这次的状态是:
1. 长度
2. 是否含有"13"
3. 前一位是否为1
4. 是否除得尽13
5. 是否是边界
如果已经有了"13",向下传递的都是true。关于能否除尽13要用到同余定理的推论吧、余数和余数乘以10加k同余。
dp[len][pre][B][mod]分别是上述状态。关于是否是边界、因为是边界就不会进行记忆化,所以不需要增加维度。
代码如下:
/*
ID: j.sure.1
PROG:
LANG: C++
*/
/****************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <climits>
#include <iostream>
#define INF 0x3f3f3f3f
using namespace std;
/****************************************/
int num[10];
int dp[10][2][2][20];
int dfs(int len, bool pre, bool B, int mod, bool bnd)
{
if(len == 0) {
if(B && mod % 13 == 0) {
//printf("who is %d\n", mod);
return 1;
}
return 0;
}
if(!bnd && dp[len][pre][B][mod] != -1)
return dp[len][pre][B][mod];
int lim = (bnd ? num[len] : 9);
int ret = 0;
for(int k = lim; k >= 0; k--) {
int nm = (mod*10+k) % 13;
ret += dfs(len-1, k==1, B||(pre&&k==3), nm, bnd&&k==lim);
}
if(!bnd) dp[len][pre][B][mod] = ret;
return ret;
}
int Solve(int x)
{
int cnt = 0;
while(x) {
num[++cnt] = x % 10;
x /= 10;
}
return dfs(cnt, false, false, 0, true);
}
int main()
{
#ifdef J_Sure
// freopen("000.in", "r", stdin);
// freopen(".out", "w", stdout);
#endif
int n;
memset(dp, -1, sizeof(dp));
while(~scanf("%d", &n)) {
printf("%d\n", Solve(n));
}
return 0;
}