首页 > 其他 > 详细

Light OJ 1068

时间:2015-02-24 20:58:49      阅读:328      评论:0      收藏:0      [点我收藏+]

数位DP

技术分享
#include <cstdio>
#include <cstring>
using namespace std;

const int MAX_DIGIT = 15;
const int MAX_K = 10005;

long long n;
int f[MAX_DIGIT];
long long memoize[MAX_DIGIT][MAX_DIGIT * 9][MAX_DIGIT * 9];
int k;

int to_digits(long long a)
{
    int ret = 0;
    while (a > 0)
    {
        f[ret++] = a % 10;
        a /= 10;
    }
    return ret;
}

long long dfs(int digit, bool less, int sum, int remainder)
{
    if (digit < 0)
    {
        return sum == 0 && remainder == 0;
    }
    if (less && memoize[digit][sum][remainder] != -1)
    {
        return memoize[digit][sum][remainder];
    }
    int limit = less ? 9 : f[digit];
    long long ret = 0;
    for (int i = 0; i <= limit; i++)
    {
        ret += dfs(digit - 1, less || i < f[digit], (sum + i) % k, (remainder * 10 + i) % k);
    }
    if (less)
    {
        memoize[digit][sum][remainder] = ret;
    }
    return ret;
}

long long work(long long n)
{
    if (n < 0)
    {
        return 0;
    }
    if (n == 0)
    {
        return 1;
    }
    int len = to_digits(n);
    if (k >= MAX_DIGIT * 9)
    {
        return 0;
    }
    return dfs(len - 1, false, 0, 0);
}

int main()
{
    int t;
    scanf("%d", &t);
    for (int i = 1; i <= t; i++)
    {
        int a, b;
        scanf("%d%d%d", &a, &b, &k);
        memset(memoize, -1, sizeof(memoize));
        printf("Case %d: %lld\n", i, work(b) - work(a - 1));
    }
    return 0;
}
View Code

 

Light OJ 1068

原文:http://www.cnblogs.com/rainydays/p/4298906.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!