An integer is divisible by 3 if the sum of its digits is also
divisible by 3. For example, 3702 is divisible by 3 and 12(3+7+0+2) is
also divisible by 3. This property also holds for the integer 9. In
this problem, we will investigate this property for other integers.
Input The rst line of input is an integer T ( T< 100) that indicates
the number of test cases. Each case is a line containing 3 positive
integers A , B and K . 1 A B< 2 31 and 0 < K <
10000. Output For each case, output the number of integers in the range [ A;B ] which is divisible by K and the sum of its digits is
also divisible by K .
数位dp,记录当前数模k的余数和数字和模k的余数。
注意到总共只有十位数,数字之和不会很大。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define DP dp[p][m1][m2]
int dp[15][110][110],mod,l,a[15];
int dfs(int p,int m1,int m2,bool less)
{
int r,k,ret=0;
if (less&&DP>=0) return DP;
if (p==0) return m1==0&&m2==0;
r=less?9:a[p];
for (k=0;k<=r;k++)
ret+=dfs(p-1,(m1*10+k)%mod,(m2+k)%mod,less||k<r);
if (less) DP=ret;
return ret;
}
int solve(int x)
{
l=0;
while (x)
{
a[++l]=x%10;
x/=10;
}
memset(dp,0xff,sizeof(dp));
return dfs(l,0,0,0);
}
int main()
{
int x,y,T;
scanf("%d",&T);
while (T--)
{
scanf("%d%d%d",&x,&y,&mod);
if (mod>100)
{
printf("0\n");
continue;
}
printf("%d\n",solve(y)-solve(x-1));
}
}