Beautiful numbers CodeForces - 55D(数位DP)

Beautiful numbers

CodeForces - 55D

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的题目
题意:数字满足的条件是该数字可以被它的每一位非零位整除。
思路:其实我数位dp刚刚入门(其实还没入门,刚开始懂),发现其实数位dp只要理解了大部分的套路部分,核心部分就是要找到判断这个数满足条件的方法,如果找到了判断数字满足题目条件的方法那么这个题目就解决了。

这个题的条件是数字被每一位非零数整除,那么可以到的,这个数应该被每一位的最小公倍数整除,1-9的最小公倍数是2520,所以其他位数最小公倍数都在2520内,即比2520小,所以这样思路就很明显了
dfs(pos, num,lcm,limit),分别代表第几位,当前数字,当前数字所有非零位的最小公倍数,是否有限制。当前数字因为太大,而我们最终枚举完后只需要判断
num % lcm是否为0,所以每次传入的num每次模2520即可,这样就可以小很多,所以我们的dp数组可以开三维dp[pos][num][lcm],分别是第几位,数字取模后的大小,最小公倍数,这样我们至少要开19x2520x2520的大小,肯定开不了,所以对于lcm这一维我们需要进行离散化,经过打表可以发现,2520内可以整除2520的只有48个,所以我们可以离散化一下让lcm映射到1-48既可以了这样就可以开19x2520x48大小的了。

code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MOD = 2520;
int Hash[3000];
int digit[50];
ll dp[50][2530][50];
void init(){
    int cnt = 0;
    for(int i = 1; i <= MOD; i++){
        if(MOD % i == 0)
            Hash[i] = cnt++;
    }
}
ll gcd(ll a,ll b){
    if(!b)
        return a;
    else return gcd(b,a%b);
}
ll dfs(int pos,int num,int lcm,int limit){
    if(pos == -1)
        return num % lcm == 0;
    ll &dpnow = dp[pos][num][Hash[lcm]];
    if(!limit && dpnow != -1)
        return dpnow;
    int max_digit = limit ? digit[pos] : 9;
    ll ans = 0;
    for(int i = 0; i <= max_digit; i++){
        ans += dfs((pos - 1), ((num * 10 + i) % MOD), (!i ? lcm : lcm * i / gcd(lcm,i)), (limit && i == max_digit));
    }
    if(!limit) dpnow = ans;
    return ans;
}
ll solve(ll n){
    int pos = 0;
    while(n){
        digit[pos++] = n % 10;
        n /= 10;
    }
    return dfs(pos-1,0,1,1);
}
int main(){
    init();
    int t;
    cin >> t;
    memset(dp,-1,sizeof(dp));
    while(t--){
        ll l,r;
        cin >> l >> r;
        cout << solve(r) - solve(l-1) << endl;
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/codeswarrior/article/details/80434276