【Codeforces Beta Round #51】Codeforces 55D Beautiful numbers

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

被各位数字整除,就是被各位数字的最小公倍数整除。而且1..9的最小公倍数是2520,所以只要在dfs中记录当前数字对2520的余数和各位数字的最小公倍数。由于最小公倍数在2520之间的分布是很稀疏的,所以可以离散化节省空间。

#include<cstdio>
#include<cstring>
#include<iostream>
#define LL long long
#define DP dp[pos][mod][num[lcm]]
using namespace std;
const int mlcm=2520;
int num[2530],a[20],len,tot;
LL dp[20][2530][50];
int gcd(int a,int b)
{
    return b?gcd(b,a%b):a;
}
void init()
{
    memset(dp,0xff,sizeof(dp));
    int i;
    for (i=1;i<=mlcm;i++)
      if (mlcm%i==0)
        num[i]=++tot;
}
LL dfs(int pos,int mod,int lcm,bool less)
{
    int i;
    if (less&&DP>=0) return DP;
    if (pos==0)
      return mod%lcm==0;
    LL ret=0;
    int r=less?9:a[pos];
    for (i=0;i<=r;i++)
      ret+=dfs(pos-1,(mod*10+i)%mlcm,i?i*lcm/gcd(i,lcm):lcm,less||i<r);
    if (less) DP=ret;
    return ret;
}
LL qry(LL x)
{
    int i;
    LL ans=0;
    len=0;
    while (x)
    {
        a[++len]=x%10;
        x/=10;
    }
    a[len+1]=0;
    return dfs(len,0,1,0);
}
int main()
{
    int i,j,k,T;
    LL x,y,z;
    scanf("%d",&T);
    init();
    while (T--)
    {
        scanf("%I64d%I64d",&x,&y);
        printf("%I64d\n",qry(y)-qry(x-1));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值