D. Magic Numbers
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.
For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic.
Find the number of d-magic numbers in the segment [a, b] that are multiple of m. Because the answer can be very huge you should only find its value modulo 109 + 7 (so you should find the remainder after dividing by 109 + 7).
Input
The first line contains two integers m, d (1 ≤ m ≤ 2000, 0 ≤ d ≤ 9) — the parameters from the problem statement.
The second line contains positive integer a in decimal presentation (without leading zeroes).
The third line contains positive integer b in decimal presentation (without leading zeroes).
It is guaranteed that a ≤ b, the number of digits in a and b are the same and don't exceed 2000.
Output
Print the only integer a — the remainder after dividing by 109 + 7 of the number of d-magic numbers in segment [a, b] that are multiple of m.
Examples
input
Copy
2 6
10
99
output
8
input
Copy
2 0
1
9
output
4
input
Copy
19 7
1000
9999
output
6
Note
The numbers from the answer of the first example are 16, 26, 36, 46, 56, 76, 86 and 96.
The numbers from the answer of the second example are 2, 4, 6 and 8.
The numbers from the answer of the third example are 1767, 2717, 5757, 6707, 8797 and 9747.
题意:
定义d-magic数为d出现且只出现在偶数位上。问[l,r]内%m==0的d-magic数有多少个。
分析:
dp[pos][sta]表示处理到第pos位%m == sta的方案数。
对于%m==0,因为我们要枚举所有的位数,所以我们可以边累计加%m,最后判断是否为0.
具体细节看代码把,除了%m==0,其他就是数位DP的模板点。
注意:mod和要正着枚举
///求前n个数的二进制形式含有11个数的和
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=2005;
typedef long long ll;
const int mod=1e9+7;
string s1;
ll dp[maxn][maxn];
int bit[maxn];
int m,d;
int len;
ll dfs(int pos,int sta,bool limit)
{
if(pos==len) return sta==0;
if(!limit&&dp[pos][sta]!=-1)
return dp[pos][sta];
int up=(limit?bit[pos]:9);
ll ans=0;
for(int i=0;i<=up;i++)
{
if((pos&1)&&i!=d) continue;///数的位置从0开始,所以反着看
if(!(pos&1)&&i==d) continue;
ans=(ans+dfs(pos+1,(sta*10+i)%m,limit&&i==up)%mod)%mod;
}
if(!limit)dp[pos][sta]=ans;
return ans;
}
ll solve(string s)
{
len=s.length();
for(int i=0;i<len;i++)
bit[i]=s[i]-'0';
return dfs(0,0,1);
}
bool judge(string s)
{
int ok=0;
for(int i=0;i<s.length();i++){
int t=s[i]-'0';
ok=(ok*10+t)%m;
if(!(i&1)&&t==d)return false;
if((i&1)&&t!=d)return false;
}
return ok==0;
}
int main()
{
while(scanf("%d%d",&m,&d)!=-1)
{
string a,b;
cin>>a>>b;
memset(dp,-1,sizeof(dp));
cout<<(solve(b)-solve(a)+judge(a)+mod)%mod<<endl;///字符串不能-1
}
return 0;
}