Codeforces 55D - Beautiful numbers(数位dp)好

来源:互联网 发布:滇虹药业淘宝旗舰店 编辑:程序博客网 时间:2024/04/27 01:42

D. Beautiful numbers

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 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 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 tori, inclusively).

Sample test(s)
Input
11 9
Output
9
Input
112 15
Output
2


思路:如果一个数能被它的所有非零数位整除,那么可以转虎城能被它们的最小公倍数整除,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。

#include<bits/stdc++.h>using namespace std;typedef long long LL;const int MOD=2520;const int maxn=25;int N;int dig[maxn];LL l,r;LL dp[maxn][MOD+1][50];int Hash[MOD+10];LL dfs(int cur,int mod,int lcm,int e){    if(cur<0)return mod%lcm==0;    if(!e&&dp[cur][mod][Hash[lcm]]!=-1)        return dp[cur][mod][Hash[lcm]];    int end=(e?dig[cur]:9);    LL ans=0;    for(int i=0;i<=end;i++)    {        int tmp=(mod*10+i)%MOD;        int tmplcm=lcm;        if(i)tmplcm=lcm/__gcd(lcm,i)*i;        ans+=dfs(cur-1,tmp,tmplcm,e&&i==end);    }    if(!e)dp[cur][mod][Hash[lcm]]=ans;    return ans;}LL solve(LL n){    int len=0;    while(n)    {        dig[len++]=n%10;        n/=10;    }    return dfs(len-1,0,1,1);}void init(){    int cnt=0;    for(int i=1;i<=MOD;i++)        if(MOD%i==0)Hash[i]=++cnt;    memset(dp,-1,sizeof(dp));}int main(){    int T;    scanf("%d",&T);    init();    while(T--)    {        cin>>l>>r;        cout<<solve(r)-solve(l-1)<<endl;    }    return 0;}



0 0
原创粉丝点击