数位dp Beautiful numbers

题目描述:
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

大致题意:

统计一个区间内美丽数的个数。
一个数可以整除它自己的每一位数,就称这个数为美丽数。
这个代码研究了很长时间。思路注释上了。

ac代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef long long ll;
#define mod 2520
ll dp[20][mod][50];
int tem[22];
int indx[mod+5];
ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}
ll LCM(ll a,ll b)
{
    return a/gcd(a,b)*b;
}
ll dfs(int len,int pre,int lcm,bool fp)
{
    if(!len)        //到了最后一位,如果pre%lcm==0,那么pre就是一个美丽数。
        return pre%lcm==0;   //递归出口!
    if(!fp && dp[len][pre][indx[lcm]]!=-1)  //如果当前状态没有上限,并且该状态已经遍历过。那么就直接返回。
        return dp[len][pre][indx[lcm]];
    int maxn=fp?tem[len]:9;  //有上限的话,当前位最多取到tem[len],没有上限的话就可以取到9.
    ll ans=0;
    for(int i=0;i<=maxn;i++)       //遍历len位的数。
    {
        int nowsum,nowlcm=lcm;
        nowsum=(pre*10+i)%mod;
        if(i)
            nowlcm=LCM(lcm,i);        //当前数的最小公倍数。
        ans+=dfs(len-1,nowsum,nowlcm,fp && i==maxn);
    }
    if(!fp)
        dp[len][pre][indx[lcm]]=ans;  //记忆化搜索。
    return ans;
}
void init()  //这里主要是为了压缩空间。因为符合条件的i只有48个,所以可以将dp的第3维压缩到50.
{
    int i;
    int num=0;
    for(i=1;i<=2520;i++)
    {
        if(mod%i==0)
            indx[i]=++num;
    }
    memset(dp,-1,sizeof(dp));
}
ll cal(ll a)
{
    int top=0;
    while(a)
    {
        tem[++top]=a%10;
        a=a/10;
    }
    return dfs(top,0,1,1);
}
int main()
{
    int t;
    ll a,b;
    scanf("%d",&t);
    init();
    while(t--)
    {
        scanf("%I64d%I64d",&a,&b);
        printf("%I64d\n",cal(b)-cal(a-1));
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值