Beautiful numbers

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

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



今天,其实昨天开的。看了一晚上。开始搞数位dp。总结来说就是记忆化搜索,关键是选择好dp的状态和维数,需要维护的东西。只是略微知道一些吧现在算是。

这东西还是得多刷题啊。QWQ

这个题用3维。dp[i][j][k]表示处理第i位,前面的各位数字的最小公倍数为j,当前数为k的个数。

这里直接开肯定是不可能的。我们首先把这个当前数给缩一下,1~9的最小公倍数为2520.所以我们可以先对这个数取模,再判断是不是能整除j。

另外第二维可以哈希处理,可以降低空间。

具体的可以搜一下大神们的题解。这个题是比较经典的了。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;
const int max_lcm = 2520;
int lcm(int a,int b)
{
    return a/__gcd(a,b)*b;
}
long long dp[20][50][2525];
int ha[2525];
int num[20];
long long dfs(int len,int pre_lcm,int pre_num,int up)
{
    if(!len)return pre_num%pre_lcm == 0;
    if(!up && dp[len][ha[pre_lcm]][pre_num] != -1)return dp[len][ha[pre_lcm]][pre_num];
    int n = up?num[len] : 9;
    long long res = 0;
    for(int i = 0 ; i <= n ; ++i)
    {
        int now_num = (pre_num*10+i)%max_lcm;
        int now_lcm = pre_lcm;
        if(i)now_lcm = lcm(now_lcm,i);
        res += dfs(len-1,now_lcm,now_num,up && i == n);
    }
    if(!up)dp[len][ha[pre_lcm]][pre_num] = res;
    return res;
}
long long cal(long long x)
{
    int len = 0;
    while(x)
    {
        num[++len] = x%10;
        x/=10;
    }
    return dfs(len,1,0,1);
}
int main()
{
    int t;
    int cnt = 0;
    for(int i = 1 ; i <= 2520; ++i)if(max_lcm % i ==0)ha[i] = cnt++;
    memset(dp,-1,sizeof dp);
    scanf("%d",&t);
    long long l,r;
    while(t--)
    {
        scanf("%I64d %I64d",&l,&r);
        printf("%I64d\n",cal(r) - cal(l-1));
    }
    return 0;
}







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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值