CodeForces 55D Beautiful numbers 数位dp

7 篇文章 0 订阅

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

Example

Input

1
1 9

Output

9

Input

1
12 15

Output

2

题意:求出[l,r]中能被它的每一位数整除的数。

题解:定义dp[i][j][k]表示第i位时,选出数的lcm为j,这个数mod2520(lcm(1~9))的结果为k的数目。
最后判断是否合法就是看k%j是否为0。

但这样需要2520*2520*18 的数组,会MLE,又因为1~9的任意组合的lcm只有48个,所以可以把它们映射一下。(…这个很巧妙!对于很多时候可能会有冗余的状态,我们可以把它们省去)

其实我比较不解0为什么可以出现在其中。

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

const int N = 25;
const int M = 2521;
const int NN = 49;

ll l,r;
int a[N],mp[M];
ll dp[N][NN][M];

int gcd(int a,int b) {return b==0?a:gcd(b,a%b);}
int lcm(int a,int b) {return a*b/gcd(a,b);}

void in_it(){
    int cnt=0;
    for(int i=1;i<=2520;i++){
        if(2520%i==0) mp[i]=++cnt;
    }
}

ll dfs(int pos,int mod,int lc,bool limit){
    if(pos<=0) return (mod%lc==0);
    if(!limit&&dp[pos][mp[lc]][mod]!=-1) return dp[pos][mp[lc]][mod];
    int mx;if(limit) mx=a[pos];
    else mx=9;ll ans=0;
    for(int i=0;i<=mx;i++){
        if(i==0) ans+=dfs(pos-1,(mod*10+i)%2520,lc,limit&&i==mx);
        else ans+=dfs(pos-1,(mod*10+i)%2520,lcm(lc,i),limit&&i==mx);
    }
    if(!limit) dp[pos][mp[lc]][mod]=ans;
    return ans;
}

ll getans(ll x){
    int cnt=0;
    while(x){
        a[++cnt]=x%10;
        x/=10;
    }
    return dfs(cnt,0,1,1);
}

int t;
int main(){
    scanf("%d",&t);in_it();
    memset(dp,-1,sizeof(dp));   
    while(t--){
       scanf("%I64d%I64d",&l,&r);
       cout<<getans(r)-getans(l-1)<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值