Descirption D e s c i r p t i o n
一个美丽数就是可以被它的每一位非零数字整除的数。
要求寻找区间 [l,r] [ l , r ] 内的美丽数的数目。
Solution S o l u t i o n
首先是计数问题的老套路,将 [l,r] [ l , r ] 转化为 [1,r]−[1,l−1] [ 1 , r ] − [ 1 , l − 1 ] 。
接下来考虑问题,假设 N=a1a2a3⋯an¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ N = a 1 a 2 a 3 ⋯ a n ¯ ,且对 ∀ai≠0,i≤n ∀ a i ≠ 0 , i ≤ n ,均有 ai|N a i | N 。则一定有 lcmai≠0(ai)|N l c m a i ≠ 0 ( a i ) | N 。这样一来,我们就可以用 d(i,j,k) d ( i , j , k ) 表示处理到第 i i 位,当前数模 的余数为 j j ,当前所有数字的最小公倍数为 时的方案数。
具体操作:
- 先将得到的数按位拆开进行 dfs() d f s ( ) 。
- dfs() d f s ( ) 从低位走向高位,实际操作时还要多加一维,表示枚举的数是否已经碰到顶了(给定的数),举个例子就是给定一个数 2430 2430 。当前枚举第三位是 2 2 的话,第二位就是 ~ 9 9 之间任意一个数,而第三位是 的话,第二位只能取 1 1 ~ 。
最后一个主意事项,如果按刚才的办法开数组要开到 19∗2520∗2520 19 ∗ 2520 ∗ 2520 是要爆内存的,仔细想一想,其实 k k 的取值范围并不大,很明显的 ,而 2520=23∗32∗5∗7 2520 = 2 3 ∗ 3 2 ∗ 5 ∗ 7 。所以 2520 2520 总共也只有 (3+1)∗(2+1)∗(1+1)∗(1+1)=48 ( 3 + 1 ) ∗ ( 2 + 1 ) ∗ ( 1 + 1 ) ∗ ( 1 + 1 ) = 48 个因子而已,所以可以对第三维进行离散化,将空间降到 19∗2520∗48 19 ∗ 2520 ∗ 48 ,这样就满足要求了。
Code C o d e
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAXN 25
#define MOD 2520
#define LL long long
LL d[MAXN][MOD][48];
int index[MOD + 10], bit[MAXN];
int gcd(int a, int b) {
return b ? gcd(b, a % b) : a;
}
int lcm(int a, int b) {
return a * b / gcd(a,b);
}
LL dfs(int pos, int preSum, int preLcm, bool flag) {
if (pos == 0)
return preSum % preLcm == 0;
if (!flag && d[pos][preSum][index[preLcm]] != -1)
return d[pos][preSum][index[preLcm]];
LL ans = 0;
int upper = flag ? bit[pos] : 9;
for (int i = 0; i <= upper; i++) {
int nowSum = (preSum * 10 + i) % MOD;
int nowLcm = preLcm;
if (i)
nowLcm = lcm(nowLcm,i);
ans += dfs(pos - 1, nowSum, nowLcm, flag && i == upper);
}
if (!flag)
d[pos][preSum][index[preLcm]] = ans;
return ans;
}
LL calc(LL x) {
int pos = 0;
while (x) {
bit[++pos] = x % 10;
x /= 10;
}
return dfs(pos, 0, 1, 1);
}
int main() {
int T;
LL l, r;
int num = 0;
for (int i = 1; i <= MOD; i++)
if (MOD % i == 0)
index[i] = num++;
memset(d, -1, sizeof d);
scanf("%d", &T);
while (T--) {
std::cin >> l >> r;
std::cout << calc(r) - calc(l - 1) << std::endl;
}
return 0;
}