CodeForces 55D Beautiful numbers

Beautiful numbers

Description

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).

Sample Input

Input
1
1 9
Output
9
Input
1
12 15
Output
2

题意是给出一个范围,求这个范围中beautiful number的数量,beautiful number就是指一个数能被自身各个位置上的数整除。
显然的,beautiful number自身一定要被各位上的数的最小公倍数整除。0~9的最小公倍数种类实际上是很少的,也是很小的(2520)。因此可以用dp[20][50][2521]来保存状态。dp[pos][id][lcm], id指的是某种最小公倍数。因为最小公倍数最大只有2520,所以可以num %= 2520,答案不变。接下来就可以上数位dp模板了

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
#define ll long long

int dig[50];
ll dp[20][50][2521];
int id[2521];

ll getlcm(ll a, ll b) {
    return a / __gcd(a, b) * b;
}

ll dfs(int pos, ll lcm, ll sum, int lim) {
    if(pos == -1) return sum % lcm == 0;
    if(dp[pos][id[lcm]][sum] != -1 && !lim) return dp[pos][id[lcm]][sum];
    int End = lim ? dig[pos] : 9;
    ll ret = 0;
    for(int i = 0; i <= End; i++) {
        ll nlcm = lcm;
        if(i) nlcm = getlcm(nlcm, i);
        ll nsum = sum * 10 + i;
        if(pos) nsum %= 2520;
        ret += dfs(pos - 1, nlcm, nsum, i == End && lim);
    }
    if(!lim) dp[pos][id[lcm]][sum] = ret;
    return ret;
}

ll func(ll a) {
    int n = 0;
    while(a) {
        dig[n++] = a % 10;
        a /= 10;
    }
    return dfs(n - 1, 1, 0, 1);
}

void init() {
    int tmp = 0;
    for(int i = 1; i <= 2520; i++) if(2520 % i == 0) id[i] = tmp++;
    memset(dp, -1, sizeof(dp));
}

int main() {
    int t;
    init();
    scanf("%d", &t);
    while(t--) {
        ll a, b;
        scanf("%I64d %I64d", &a, &b);
        printf("%I64d\n", func(b) - func(a - 1));
    }
}

 

 

转载于:https://www.cnblogs.com/lonewanderer/p/5654599.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值