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

题意:
问所给区间内,有多少个数字,可以整除数位上的每一个正整数。
思路:
数位上可能的九个数字,最大的lcm就是2520.
dfs中的参数设为除以2520的模数md,和之前数位的lcm即可。
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>

#define fuck(x) cout<<#x<<" = "<<x<<endl;
#define ls (t<<1)
#define rs ((t<<1)+1)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 100086;
const int inf = 2.1e9;
const ll Inf = 999999999999999999;
const int mod = 1000000007;
const double eps = 1e-6;
const double pi = acos(-1);
vector<int> sca;
int bit[20];
ll dp[20][50][2600];

ll LCM(ll a, ll b) {
    if (b == 0) { return a; }
    return a * b / __gcd(a, b);
}

ll dfs(int pos, ll lcm, ll md, bool limit) {
    int t = lower_bound(sca.begin(), sca.end(), lcm) - sca.begin();
    if (pos == -1) {
        if (md % lcm == 0) { return 1; }
        else { return 0; }
    }
    if (!limit&&dp[pos][t][md] != -1) { return dp[pos][t][md]; }
    ll ans = 0;
    int up = limit ? bit[pos] : 9;
    for (int i = 0; i <= up; i++) {
        ans += dfs(pos - 1, LCM(lcm, i), (md * 10 + i) % 2520, limit && i == up);
    }
    if (!limit) {
        dp[pos][t][md] = ans;
    }
    return ans;
}

ll solve(ll a) {
    if(a==0){ return 0;}
    int pos = 0;
    while (a) {
        bit[pos++] = a % 10;
        a /= 10;
    }
    return dfs(pos-1, 1, 0, true)-1;
}

int main() {
    sca.push_back(0);
    for (int i = 1; i <= 2520; i++) {
        if (2520 % i == 0) { sca.push_back(i); }
    }
    memset(dp, -1, sizeof(dp));
    int T;
    scanf("%d", &T);
    while (T--) {
        ll a, b;
        scanf("%lld%lld", &a, &b);
        printf("%lld\n", solve(b)-solve(a-1));
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/ZGQblogs/p/10677971.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值