【题解】CodeForces 55D Beautiful numbers

3 篇文章 0 订阅
1 篇文章 0 订阅

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,l1] [ 1 , r ] − [ 1 , l − 1 ]

接下来考虑问题,假设 N=a1a2a3an¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ N = a 1 a 2 a 3 ⋯ a n ¯ ,且对 ai0,in ∀ a i ≠ 0 , i ≤ n ,均有 ai|N a i | N 。则一定有 lcmai0(ai)|N l c m a i ≠ 0 ( a i ) | N 。这样一来,我们就可以用 d(i,j,k) d ( i , j , k ) 表示处理到第 i i 位,当前数模 2520=lcm(1,2,,9) 的余数为 j j ,当前所有数字的最小公倍数为 k 时的方案数。

具体操作:

  • 先将得到的数按位拆开进行 dfs() d f s ( )
  • dfs() d f s ( ) 从低位走向高位,实际操作时还要多加一维,表示枚举的数是否已经碰到顶了(给定的数),举个例子就是给定一个数 2430 2430 。当前枚举第三位是 2 2 的话,第二位就是 1 ~ 9 9 之间任意一个数,而第三位是 3 的话,第二位只能取 1 1 ~ 4

最后一个主意事项,如果按刚才的办法开数组要开到 1925202520 19 ∗ 2520 ∗ 2520 是要爆内存的,仔细想一想,其实 k k 的取值范围并不大,很明显的 k|2520,而 2520=233257 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 个因子而已,所以可以对第三维进行离散化,将空间降到 19252048 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值