Codeforces 55D. Beautiful numbers

 

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

 

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

一个数能被它的所有非零数位整除,则能被它们的最小公倍数整除,而1到9的最小公倍数为2520,离散化记录每个最小公倍数,开三维状态[数位][数字和][最小公倍数]记录答案数,动(sou)规(suo)即可。

 

 1 /*by SilverN*/
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<cmath>
 7 #define LL long long
 8 using namespace std;
 9 int num[2550],cnt=0;
10 int lim[50],lct=0;
11 LL f[24][2520][50];
12 LL n,m;
13 LL gcd(LL a,LL b){
14     if(!b)return a;
15     return gcd(b,a%b);
16 }
17 LL dp(int pos,int smm,int lcm,bool flag){
18     //      当前位置  当前和  当前最小公倍数 是否在上界
19     if(!pos)return (smm%lcm==0);
20     if(!flag && f[pos][smm][num[lcm]]!=-1)return f[pos][smm][num[lcm]];
21     LL res=0;
22     int limit=9;if(flag)limit=lim[pos];
23     for(int i=0;i<=limit;i++){
24         int psmm=(smm*10+i)%2520;
25         int plcm=lcm;
26         if(i){plcm=lcm/gcd(lcm,i)*i;}
27         res+=dp(pos-1,psmm,plcm,flag&&i==limit);
28     }
29     if(!flag)f[pos][smm][num[lcm]]=res;
30     return res;
31 }
32 LL divi(LL x){
33     lct=0;
34     while(x){
35         lim[++lct]=x%10;
36         x/=10;
37     }
38     return dp(lct,0,1,1);
39 }
40 int main(){
41     int i,j;
42     for(i=1;i<=2520;i++){
43         if(2520%i==0)
44             num[i]=++cnt;
45     }
46     memset(f,-1,sizeof f);
47     int T;
48     scanf("%d",&T);
49     while(T--){
50         scanf("%I64d%I64d",&n,&m);
51         printf("%I64d\n",divi(m)-divi(n-1));
52     }
53     return 0;
54 }

 

 

posted @ 2016-09-29 16:29  SilverNebula  阅读(824)  评论(0编辑  收藏  举报
AmazingCounters.com