题目描述
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整除的数,毫无疑问n又是一个超级大的数,那么一定是我们的数位dp啦,只要是熟练运用我们的模板,就改一小下就可以啦,下面请看代码详细的叙述
补充:模运算对于乘法加法减法都是满足结合律分配律的
#include<iostream>
#include<cstring>
using namespace std;
const int N = 30;
typedef long long LL;
LL f[N][N][N],a[N];
LL dp(int pos,int mo,int flag1,int flag2){//mo表示的目前dp的这个数对13的取模是多少
if(!pos) return flag1 ==2 && mo==0;//如果到头了已经有13了而且是13的倍数就返回1,否则返回0
if(f[pos][mo][flag1] != -1 && flag2) return f[pos][mo][flag1];
int x = flag2 ? 9 : a[pos];
LL ans = 0;
for(int i=0;i<=x;i++){
int flag = flag1;
if(flag == 0 && i == 1) flag = 1;//就是前面没有13而且上一个也不是1,这一位是1,就把flag
//设置成1
if(flag == 1 && i == 3) flag = 2;//如果前面没有13,上一个是1,这一个是3,就把flag设置成2
//2代表有13
if(flag == 1 && i != 1 && i != 3) flag = 0;//如果前面没有13,上一个是1,这一个既不是1也不
//是3,就把他设置成0
ans += dp(pos-1,(mo*10+i)%13,flag,flag2||i<x);
}
return flag2 ? f[pos][mo][flag1] = ans : ans;//写的帅一点哈哈哈,其实除了帅并没有其他用
}
LL solve(LL n){
memset(f,-1,sizeof f);
int tot = 0;
while(n) a[++tot] = n%10,n/=10;
return dp(tot,0,0,0);
}
int main(){
LL n;
while(cin>>n) cout<<solve(n)<<endl;
return 0;
}