codeforces 55D Beautiful numbers(数位dp)

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
题意:如果一个数能够被组成它的各个非0数字整除,则称它是完美数。例如:1-9都是完美数,10,11,12,101都是完美数,但是13就不是完美数(因为13不能被数字3整除)。
现在给定正整数x,y,求x和y之间(包含x和y的闭区间)共有多少完美数。
思路:

数位DP经典好题。 首先状态不好想。 dp[i][j][k] 表示到弟i位对2520取模后为j,各位的lcm为k的数字个数。
为什么要这样是因为同余定理(a*10 + b)%2520 =  (a%2520*10 + b) % 2520 。因为1-9的最小公倍数不会超过2520,
那么就可以写出式子。 还有个优化。因为19*2520*2520太大, 会mle, 所以可以优化下第三维,因为最小公倍数都是离散的, 所以可以hash记录下。

#include <cstdio>
#include <map>
#include <iostream>
#include<cstring>
#define ll long long int
#define M 6
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1};
int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1};
const int inf=0x3f3f3f3f;
const ll mod=1e9+7;
ll l,r;
int bits[20];
ll dp[20][3000][50]; //表示 i位数 当前为j(对2520求余后) 的最小公倍数为k  
int hashh[3000];
void init(){
    memset(dp,-1,sizeof(dp));
    int cnt=0;
    for(int i=1;i<=2520;i++){
        if(2520%i==0) hashh[i]=cnt++;
    }
}
ll dfs(int len,int num,int mo,bool ismax){
    if(!len)
    return num%mo==0;
    if(!ismax&&dp[len][num][hashh[mo]]>=0)
    return dp[len][num][hashh[mo]];
    ll cnt=0;
    int up=ismax?bits[len]:9;
    for(int i=0;i<=up;i++){
        if(i==0) cnt+=dfs(len-1,(num*10+i)%2520,mo,ismax&&i==up);
        else cnt+=dfs(len-1,(num*10+i)%2520,lcm(mo,i),ismax&&i==up);
    }
    if(!ismax) dp[len][num][hashh[mo]]=cnt;
    return cnt;
}
ll solve(ll x){
    int pos=0;
    while(x){
        bits[++pos]=x%10;
        x/=10;
    }
    return dfs(pos,0,1,true);
}
int main(){
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    init();
    while(t--){
        cin>>l>>r;
        cout<<solve(r)-solve(l-1)<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wmj6/p/10444687.html