CF 55D 数位DP

D. Beautiful numbers

time limit per test 4 seconds

memory limit per test 256 megabytes

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

Sample Input
Input
1
1 9
Output
9
Input
1
12 15
Output
2


题目大意:

一个整数如果能被它的所有非零数位整除,那么称这个数字为美丽数字。求给定区间内美丽数字的个数。

思路:

看一个结论(证明略):如果一个数是美丽数字,那么这个数必定能被它的所有非零数位的最小公倍数整除。相反,如果一个数能被它的所有非零数位的最小公倍数整除,那么这个数是美丽数字。

有了这个结论就可以进行数位dp了,记忆化搜索。已知1~9的lcm是2520。
dp[i][j][k]表示处理到第i位,这个数(包含第i位)对2520取余是j,所有位的lcm是k的数的个数。如果j对k取余等于0,则这些数是美丽数字。

k的范围是1~2520,这样会超内存,所以伴有离散化过程,所有情况的数位lcm也就48个。

#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
const int mod=2520; //1~9的lcm为2520
int gcd(int a,int b) {
    if(b==0) return a;
    return gcd(b,a%b);
}
int lcm(int a,int b) {
    if(a==0) return b;
    if(b==0) return a;
    return a*b/gcd(a,b);
}
int index[2525];
int initIndex() {
    int tmp = 0;
    for(int i=1;i<=2520;i++)
        if(2520%i==0) index[i] = tmp++;
}
long long dp[25][mod][50];
int bit[25];
long long dfs(int pos,int prenum,int prelcm,bool flag) { //flag为true的话表示当前位触顶了
    if(pos==-1) return prenum%prelcm == 0;
    if(!flag && dp[pos][prenum][index[prelcm]]!=-1) return dp[pos][prenum][index[prelcm]];
    int e = flag?bit[pos]:9;
    long long ans=0;
    for(int i=0;i<=e;i++) {
        ans += dfs(pos-1,(prenum*10+i)%mod,lcm(prelcm,i),flag&&i==e);
    }
    if(!flag) return dp[pos][prenum][index[prelcm]]=ans;
    return ans;
}

long long solve(long long n) {
    int pos=0;
    while(n) {
        bit[pos++] = n%10;
        n/=10;
    }
    return dfs(pos-1,0,1,true);
}
int main() {
    int T;
    long long l,r;
    initIndex();
    memset(dp,-1,sizeof(dp));
    cin>>T;
    while(T--) {
        cin>>l>>r;
        cout<<solve(r)-solve(l-1)<<endl;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值