Codeforces Beta Round #51 D. Beautiful numbers 数位dp

D. Beautiful numbers

Time Limit: 20 Sec

Memory Limit: 256 MB

题目连接

http://codeforces.com/contest/55/problem/D

Description

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).

Sample Input

1
1 9

Sample Output

9

HINT

题意

问你l-r间有多少个数,可以整除他的每个位置上的非0数

题解:

dp[i][j][k]表示,现在考虑到了第i位,在该位我用j之后,的lcm,以及各个数位的lcm为k的种类数(好绕。。。

1-9的lcm是2520,于是我们dp[20][2520][2520]就好了,但是显然我们第三维可以离散化一发,这样空间就开的下了~

然后跑数位dp就好了~

代码:

#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;

char num[30];
long long dp[20][2527][60];
int Lcm[2527];
long long gcd(long long a,long long b)
{
    if(b==0)
        return a;
    return gcd(b,a%b);
}
long long dfs(int p,int mod,int lcm,int limit)
{
    if(p<0)return (mod%lcm == 0);
    if(!limit && ~dp[p][mod][Lcm[lcm]])
        return dp[p][mod][Lcm[lcm]];
    int e = limit?num[p]:9;
    long long res = 0;
    for(int i=0;i<=e;i++)
        res+=dfs(p-1,(mod*10+i)%2520,i!=0?i*lcm/gcd(i,lcm):lcm,limit&&i==e);
    if(!limit)dp[p][mod][Lcm[lcm]]=res;
    return res;
}
long long solve(long long x)
{
    int Num = 0;
    while(x)
    {
        num[Num++]=x%10;
        x/=10;
    }
    return dfs(Num-1,0,1,1);
}
int main()
{
    int t;scanf("%d",&t);
    for(int i=1,j=0;i<=2520;i++)
        if(2520%i==0)
            Lcm[i]=j++;
    memset(dp,-1,sizeof(dp));
    for(int i=0;i<t;i++)
    {
        long long l ,r;
        scanf("%lld%lld",&l,&r);
        printf("%lld
",solve(r)-solve(l-1));
    }
}
原文地址:https://www.cnblogs.com/qscqesze/p/4988034.html