CodeForces -55D - D. Beautiful numbers(数位dp)

D. Beautiful numbers

time limit per test

4 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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

Examples

input

Copy

1
1 9

output

Copy

9

input

Copy

1
12 15

output

Copy

2

题意:给你两个数l,r(l,r<=9e18),求区间[l,r]中能被其每一个数位都整除的数字个数。

思路:

数位dp。能被其每一个数位都整除,即能整除它们的lcm。但是lcm是我们再dfs到最后一位时才会知道。

发现1~9的lcm最大为2520,因此我们可以把数对2520取模,最后看能否整除每一数位的lcm即可。

由于数组大小限制,我们将合法的lcm预处理到一个hash表中(不超过50)。

代码:

#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
#include<cmath>
#include<algorithm>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxn=20;
ll a[maxn],c[2525];
ll dp[maxn][50][2525];
ll gcd(ll x,ll y){return y==0?x:gcd(y,x%y);}
ll cal(ll x,ll y)
{
    return x/gcd(x,y)*y;
}
ll dfs(int pos,int lcm,int res,bool limit)
{
    if(pos==-1) return (res%lcm==0);
    if(!limit&&dp[pos][c[lcm]][res]!=-1) return dp[pos][c[lcm]][res];
    int up=limit?a[pos]:9;
    ll tmp=0;
    for(int i=0;i<=up;i++)
    {
        if(i) tmp+=dfs(pos-1,cal(i,lcm),(res*10+i)%2520,limit&&i==a[pos]);
        else tmp+=dfs(pos-1,lcm,(res*10+i)%2520,limit&&i==a[pos]);
    }
    if(!limit) dp[pos][c[lcm]][res]=tmp;
    return tmp;
}
ll solve(ll x)
{
    int pos=0;
    while(x)
    {
        a[pos++]=x%10;
        x/=10;
    }
    ll ans=0;
    ans=dfs(pos-1,1,0,1);
    return ans;
}
int main()
{
    int ct=0;
    for(int i=1;i<2525;i++)
    if(2520%i==0){
        c[i]=ct++;
    }
    memset(dp,-1,sizeof(dp));
    int T,cas=1;
    ll l,r;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld",&l,&r);
        printf("%lld\n",solve(r)-solve(l-1));
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值