数位dp CF 55D Beautiful numbers

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
#include
#include
#include
#include
#include
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;
}


你可能感兴趣的:(数位dp)