数位dp CF 55D Beautiful numbers

本文介绍了一种算法,用于计算指定范围内所有 beautiful numbers 的数量。Beautiful number 被定义为能够被其所有非零数字整除的正整数。通过使用动态规划方法,文章详细解释了如何高效地解决这一问题。
D. Beautiful numbers
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number isbeautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.

Input

The first line of the input contains the number of cases t (1?≤?t?≤?10). Each of the nextt lines contains two natural numbers li andri (1?≤?li?≤?ri?≤?9?·1018).

Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to usecin (also you may use %I64d).

Output

Output should contain t numbers — answers to the queries, one number per line — quantities of beautiful numbers in given intervals (fromli to ri, inclusively).

Sample test(s)
Input
1
1 9
Output
9
Input
1
12 15
Output
2

题意:如果一个数能被这个数中包含的所有数字整除,那么他就是一个beautiful number。求出[L,R]之间有多少个这样的beautiful number

思路:能同时被多个数整除就是能被他们的最小公倍数整除,可以算出最大的最小公倍数是2520,其中其余不是最大的最小公倍数都能整除2520.所以只有48个不同的最小公倍数,所以我们用dp[i][j][k] 表示i位数,前缀的数%2520为j,前缀的最小公倍数为k的数有多少个。

代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
#define eps 1e-8
#define mod 2520
#define LL long long
int Index[mod+10];
LL dp[19][mod][48] , digit[20];

int gcd(int a,int b)
{
    while (a && b)
    {
        if ( a > b ) a %= b;
        else b %= a;
    }
    return a+b;
}

int lcm(int a,int b)
{
    int g = gcd(a,b);
    return a/g*b;
}

void init()
{
    int cnt = 0;
    for (int i = 1 ; i <= mod ; ++i) if (mod%i==0) 
        Index[i] = cnt++;
    memset(dp,-1,sizeof(dp));
}

LL dfs(int pos,LL sum,int Lcm,bool limit)
{
    if (pos==-1) return sum%Lcm == 0;
    if (!limit && dp[pos][sum][Index[Lcm]] !=-1) 
        return dp[pos][sum][Index[Lcm]];
    int end = limit ? digit[pos] : 9;
    LL ret = 0;
    for (int i = 0 ; i <= end ; ++i)
    {
        int nowSum = (sum*10+i)%mod;
        int nowLcm = Lcm;
        if (i) nowLcm = lcm(nowLcm,i);
        ret += dfs(pos-1,nowSum,nowLcm,limit && i==end);
    }
    if (!limit) dp[pos][sum][Index[Lcm]] = ret;
    return ret;
}

LL Ans(LL x)
{
    int pos = 0;
    while (x)
    {
        digit[pos++] = x %10;
        x /= 10;
    }
    return dfs(pos-1,0,1,true);
}

int main()
{
    init();
    LL l , r;
    int T; cin>>T;
    while (T--)
    {
        cin>>l>>r;
        cout << Ans(r)-Ans(l-1) << endl;
    }
    //cout << max_lcm << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值