vjudge A - Beautiful numbers

本文介绍了一种使用数位动态规划(数位DP)的方法来解决一类特殊问题:计算在给定范围内有多少个“美丽数”。美丽数是指能够被其所有非零数字整除的正整数。文章详细解释了算法思路,包括如何通过二进制记录已包含的数字以及对2520取模的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
思路:数位DP。
被每一位整除则用二进制记录已经包括的数字的个数,以及对2520取模后的状态。
由于对5整除当且仅当最后一个数为0或5,对2整除当且仅当最后一个数为偶数,且1~9的最小公倍数为2520,不包括2,5后的最小公倍数为252。
所以除最后一层对2520取模,其余时候都对252取模即可。
由于整除的状态有限,最多只有48个,于是我们预处理出这48个数,并来一个映射就好(不然会TLE)。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int t,cnt;
long long l,r;
int num[20],a[2521];
long long dp[20][260][50];
int gcd(int x,int y){
    return x==0?y:gcd(y%x,x);
}
long long dfs(int pos,int x,int y,bool limite){
    if(pos==-1)    return x%y==0;
    if(dp[pos][x][a[y]]!=-1&&!limite)    return dp[pos][x][a[y]];
    int up=limite?num[pos]:9;
    long long tmp=0;
    for(int i=0;i<=up;i++)
        tmp+=dfs(pos-1,pos?(x*10+i)%252:(x*10+i),i?y*i/gcd(y,i):y,limite&&i==num[pos]);
    if(!limite)    dp[pos][x][a[y]]=tmp;
    return tmp;
}
long long slove(long long now){
    int pos=0;
    while(now){
        num[pos++]=now%10;
        now/=10;
    }
    return dfs(pos-1,0,1,1);
}
int main(){
    scanf("%d",&t);
    for(int i=1;i<=2520;i++)
        if(2520%i==0)
            a[i]=cnt++;
    memset(dp,-1,sizeof(dp));
    while(t--){
        scanf("%I64d%I64d",&l,&r);
        cout<<slove(r)-slove(l-1)<<endl;
    }
} 

 

 

 

转载于:https://www.cnblogs.com/cangT-Tlan/p/7641897.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值