Beautiful numbers

来源:互联网 发布:vue.js事件对象event 编辑:程序博客网 时间:2024/05/16 15:42

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
11 9
Output
9
Input
112 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;}