CF 55D Beautiful Numbers(数位DP)

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




题解:
题目意思就是给你一段区间L到R,问在L到R范围内的数,有多少个满足它的的每一个数字都能整除它本身(非零位);
这一般都能想到数位DP,可怎么DP呢?
首先,对于 若 a=b(mod m) 且 d|m
则 a=b(mod d)
则假设b已经模过m了,则b%d=b%m%d;

由大数取模 num=(num*10+i)%mod;

1,2,3...9的lcm为2520;
所以,num%2520%lcm=num%lcm=0是满足题意的;
由于lcm是变化的,所以我们先让其统一对2520取模(为了压缩空间在2520范围之内),后面呢,只要判断Mod对lcm取模是否为0即可;

我们设: dp[pos][Mod][Lc]:表示第pos位,模2520后数值为Mod,这pos位数字的lcm为LC;
对于下一位是0的情况,lcm保持不变,
其他情况就是 Lc=lcm(lc,i);

参考代码:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define clr(a,val) memset(a,val,sizeof(a))
 4 typedef long long ll;
 5 ll dp[20][2530][50],digit[20];
 6 int temp[2530];
 7 int t,cnt;
 8 ll L,R; 
 9 int lcm(int a,int b){return a*b/__gcd(a,b);}
10 
11 ll dfs(int pos,int Mod,int Lcm,bool limit)
12 {
13     ll ret=0;
14     if(!temp[Lcm]) temp[Lcm]=++cnt;
15     if(pos<0) return (Mod%Lcm==0);
16     if(!limit && dp[pos][Mod][temp[Lcm]]!=-1) return dp[pos][Mod][temp[Lcm]];
17     int sz=limit? digit[pos]:9;
18     for(int i=0;i<=sz;++i) ret+=dfs(pos-1,(Mod*10+i)%2520,i?lcm(Lcm,i):Lcm,limit&&(i==digit[pos]));
19     if(!limit) dp[pos][Mod][temp[Lcm]]=ret;
20     return ret;
21 }
22 
23 ll work(ll num)
24 {
25     int tmp=0;cnt=0;
26     while(num)
27     {
28         digit[tmp++]=num%10;
29         num/=10;
30     }
31     return dfs(tmp-1,0,1,1);
32 }
33 
34 int main()
35 {
36     scanf("%d",&t);clr(temp,0);clr(dp,-1);
37     while(t--)
38     {
39         scanf("%I64d%I64d",&L,&R);
40         printf("%I64d\n",work(R)-work(L-1));
41     }
42     return 0;
43 }
View Code

 



posted @ 2019-02-18 21:35  StarHai  阅读(235)  评论(0编辑  收藏  举报