codeforce 55D D. Beautiful numbers(数位dp)

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 is beautiful 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 next t lines contains two natural numbers li and ri(1 ≤ li ≤ ri ≤ 9 ·1018).

Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (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 (from li to ri, inclusively).

Examples
input
Copy
1
1 9
output
Copy
9

题解:
能被这个数的每一位整除,即能被这些数的最小公倍数整除,
1~9 的最小公倍数为2520,因此可以把这个数对2520取模,
1~9 的最小公倍数有48种组合的可能
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int mod=2520;
//2520 48
ll dp[22][2522][55];
int a[25],d[2550],vis[2550];
int gcd(int a,int b)
{
    if(b==0)return a;
    return gcd(b,a%b);
}
int lcm(int a,int b)
{
    return a/gcd(a,b)*b;
}
void init()
{
    int ans=1;
    memset(vis,-1,sizeof(vis));
    for(int i=1;i<2550;i++)
        if(mod%i==0)
        vis[i]=ans++;
}
ll dfs(int pos,int s,int LCM,int p)
{
    if(pos==-1)return s%LCM==0;
    if(!p&&dp[pos][s][vis[LCM]]!=-1)
        return dp[pos][s][vis[LCM]];
    int num=p?a[pos]:9;
    ll ans=0;
    for(int i=0;i<=num;i++)
    {
        int L=(i==0)?LCM:(lcm(LCM,i));
        int S=(s*10+i)%mod;
        ans+=dfs(pos-1,S,L,p&&i==num);
    }
    if(!p)
        dp[pos][s][vis[LCM]]=ans;
    return ans;
}
ll cal(ll x)
{
    int pos=0;
    while(x)
    {
        a[pos++]=x%10;
        x/=10;
    }
    return dfs(pos-1,0,1,1);
}
int main()
{
    init();
    memset(dp,-1,sizeof(dp));
    int T;scanf("%d",&T);
    while(T--)
    {
        ll x,y;
        scanf("%lld%lld",&x,&y);
        printf("%lld\n",cal(y)-cal(x-1));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/albertluf/article/details/80588399