lightoj - 1068 Investigation (数位dp)

1068 - Investigation
Time Limit: 2 second(s)Memory Limit: 32 MB

An integer is divisible by 3 if the sum of its digits isalso divisible by 3. For example, 3702 is divisible by 3 and 12 (3+7+0+2) isalso divisible by 3. This property also holds for the integer 9.

In this problem, we will investigate this property for otherintegers.

Input

Input starts with an integer T (≤ 200),denoting the number of test cases.

Each case contains three positive integers A, B and K(1 ≤ A ≤ B < 231 and 0 < K < 10000).

Output

For each case, output the case number and the number ofintegers in the range [A, B] which are divisible by K and the sumof its digits is also divisible by K.

Sample Input

Output for Sample Input

3

1 20 1

1 20 2

1 1000 4

Case 1: 20

Case 2: 5

Case 3: 64

 

思路:dp[cur][sum][mod]表示到当前为止对K取余为sum,每一位的和取余为mod的答案是多少,因为数最大到10位,每一位都是9,当k>90的时候答案就是0了,所以数组可以开下

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<climits>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=10;
int N;
int dig[maxn];
int A,B,K;
int dp[maxn][100][10*9];
int dfs(int cur,int e,int z,int mod,int sum)
{
    if(cur<0)return mod==0&&sum%K==0;
    if(!e&&!z&&dp[cur][sum][mod]!=-1)
        return dp[cur][sum][mod];
    int ans=0;
    int end=(e?dig[cur]:9);
    for(int i=0;i<=end;i++)
    {
        int tmpsum=i;
        for(int j=0;j<cur;j++)tmpsum*=10;
        tmpsum=(sum+tmpsum%K)%K;
        int tmpmod=(mod+i)%K;
        if(z&&!i)
            ans+=dfs(cur-1,e&&i==end,1,tmpmod,tmpsum);
        else
            ans+=dfs(cur-1,e&&i==end,0,tmpmod,tmpsum);
    }
    if(!e&&!z)dp[cur][sum][mod]=ans;
    return ans;
}
int solve(int n)
{
    if(K>=90)return 0;
    int len=0;
    memset(dp,-1,sizeof(dp));
    while(n)
    {
        dig[len++]=n%10;
        n/=10;
    }
    return dfs(len-1,1,1,0,0);
}
int main()
{
    int T,cas=1;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d%d",&A,&B,&K);
        printf("Case %d: %d\n",cas++,solve(B)-solve(A-1));
    }
    return 0;
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值