CodeForces55D Beautiful numbers

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
1
1 9
output
9
input
1
12 15
output
2

————————————————————————————————————

题目的意思是求一个区间有多少个数,数要求能被他的每一位整除

思路:数位dp,开3位数组记录长度位len的,到len为止和为sum的,sum容易很大,但可以知道1到9的最小公倍数为2520,所以可以对2520取模,LCM为lcm的书有多少个,然后dfs递归求解

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cstdio>
#include <set>
#include <cmath>
#include <map>
#include <algorithm>
#define INF 0x3f3f3f3f
#define MAXN 10000005
#define Mod 10001
using namespace std;
#define LL long long

LL dp[20][3000][50];
int a[20],index[3000];
int mod;

int gcd(int x,int y)
{
    return x%y==0?y:gcd(y,x%y);
}
int _lcm(int x,int y)
{
    return x*y/gcd(x,y);
}
void init()
{
    mod=1;
    for(int i=1; i<10; i++)
    {
        mod=_lcm(mod,i);
    }
    int ct=0;
    for(int i=1; i<=mod; i++)
    {
        if(mod%i==0) index[i]=ct++;
    }
    memset(dp,-1,sizeof dp);
}

LL dfs(int len,int sum,int lcm,bool limit)
{
    if(len<0)
        return sum%lcm==0;
    if(dp[len][sum][index[lcm]]!=-1&&!limit)
        return dp[len][sum][index[lcm]];
    int up=limit?a[len]:9;
    LL ans=0;
    for(int i=0; i<=up; i++)
    {
        ans+=dfs(len-1,(sum*10+i)%mod,i?_lcm(lcm,i):lcm,limit&&i==up);
    }
    return limit?ans:dp[len][sum][index[lcm]]=ans;
}

LL solve(LL x)
{
    int cnt=0;
    while(x>0)
    {
        a[cnt++]=x%10;
        x/=10;
    }
    return dfs(cnt-1,0,1,1);
}

int main()
{
    int T;
    LL n,m;
    init();
    for(scanf("%d",&T); T--;)
    {
        scanf("%lld%lld",&n,&m);
        printf("%lld\n",solve(m)-solve(n-1));
    }
    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值