codeforces 55D

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
1
1 9
output
9
input
1
12 15
output
2

题目链接:http://codeforces.com/problemset/problem/55/D

话说这是我第一次做codeforces,感觉他的提交好吊,就类似WF一样,看着好爽!!(我现在还不知道怎么在cf的题库里搜索题目,哪位大牛知道,指点一下,感激不尽!)

分析:一个数能被它的所有非零数位整除,则能被它们的最小公倍数整除,而1到9的最小公倍数为2520,数位DP时我们只需保存前面那些位的最小公倍数就可进行状态转移,到边界时就把所有位的lcm求出了,为了判断这个数能否被它的所有数位整除,我们还需要这个数的值,显然要记录值是不可能的,其实我们只需记录它对2520的模即可,这样我们就可以设计出如下数位DP:dfs(pos,mod,lcm,f),pos为当前位,mod为前面那些位对2520的模,lcm为前面那些数位的最小公倍数,f标记前面那些位是否达到上限,这样一来dp数组就要开到19*2520*2520,明显超内存了,考虑到最小公倍数是离散的,1-2520中可能是最小公倍数的其实只有48个,经过离散化处理后,dp数组的最后一维可以降到48,这样就不会超了。  

分析链接:http://www.cnblogs.com/algorithms/archive/2012/09/02/2668021.html

题解:看了好几天,最后弄了个容易懂的代码(如上),看懂了,首先要把那个数对2520取模(因为这个数如果想要符合的话,首先要被2520整除,因为2520是1~9的lcm),这只是第一个条件(此时取模之后存在mod参数之中),第二个条件是对所有出现过的位数上的值取模,如果mod对位数上取模==0,就可以了。

#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;

#define N 19
#define MOD 2520
typedef __int64 LL;
int t[50],cnt;
LL dp[N][MOD][48];
int dig[N];

int GCD(int a,int b) {return b?GCD(b,a%b):a;}
int LCM(int a,int b) {return a/GCD(a,b)*b;}

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

int Binary_search(int x)
{
    int mid,l=0,r=cnt;
    while(l<r-1)
    {
        mid=l+r>>1;
        if (t[mid]>x) r=mid;
        else l=mid;
    }
    return l;
}

LL dfs(int pos,int mod,int lcmid,bool f)
{
    if (pos<0) return !(mod%t[lcmid]);
    LL &aa=dp[pos][mod][lcmid];
    if (!f&&aa!=-1) return aa;
    int end=f?dig[pos]:9;
    LL res=0;
    for (int i=0;i<=end;i++)
    {
        int nmod=(mod*10+i)%MOD;
        int nlcmid=lcmid;
        if (i) nlcmid=Binary_search(LCM(t[lcmid],i));
        res+=dfs(pos-1,nmod,nlcmid,f&&i==end);
    }
    return f?res:aa=res;
}

LL sol(LL x)
{
    int ind=0;
    dig[0]=0;//这个一定不要少了,如果没有这个,1 9的时候会错
    for (;x;x/=10) dig[ind++]=x%10;
    dfs(ind-1,0,0,1);
}

int main()
{
    int o;
    cin>>o;
    init();
    while(o--)
    {
        LL x,y;
        cin>>x>>y;
        cout<<sol(y)-sol(x-1)<<endl;
    }

    return 0;
}
原文地址:https://www.cnblogs.com/s1124yy/p/5573573.html