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%20%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);
参考代码:
- #include<bits/stdc++.h>
- using namespace std;
- #define clr(a,val) memset(a,val,sizeof(a))
- typedef long long ll;
- ll dp[20][2530][50],digit[20];
- int temp[2530];
- int t,cnt;
- ll L,R;
- int lcm(int a,int b){return a*b/__gcd(a,b);}
- ll dfs(int pos,int Mod,int Lcm,bool limit)
- {
- ll ret=0;
- if(!temp[Lcm]) temp[Lcm]=++cnt;
- if(pos<0) return (Mod%Lcm==0);
- if(!limit && dp[pos][Mod][temp[Lcm]]!=-1) return dp[pos][Mod][temp[Lcm]];
- int sz=limit? digit[pos]:9;
- for(int i=0;i<=sz;++i) ret+=dfs(pos-1,(Mod*10+i)%2520,i?lcm(Lcm,i):Lcm,limit&&(i==digit[pos]));
- if(!limit) dp[pos][Mod][temp[Lcm]]=ret;
- return ret;
- }
- ll work(ll num)
- {
- int tmp=0;cnt=0;
- while(num)
- {
- digit[tmp++]=num%10;
- num/=10;
- }
- return dfs(tmp-1,0,1,1);
- }
- int main()
- {
- scanf("%d",&t);clr(temp,0);clr(dp,-1);
- while(t--)
- {
- scanf("%I64d%I64d",&L,&R);
- printf("%I64d\n",work(R)-work(L-1));
- }
- return 0;
- }
- View Code
来源: http://www.bubuko.com/infodetail-2959775.html