CF55D:Beautiful numbers(数位dp + 数论)

reference:http://blog.csdn.net/lvshubao1314/article/details/43907225

D. Beautiful numbers
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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

题意:求区间内有多少个数,其本身能被各个位上的数字整除。

思路:略。

# include <stdio.h>
# include <string.h>
# define LL long long
# define MOD 2520
LL a[21], index[2521], dp[21][MOD][50];
void init()
{
    int num = 0;
    for(int i=1; i<=MOD; ++i)
        if(!(MOD%i))
            index[i] = num++;//最小公倍数离散化,优化内存。
}

int gcd(int a, int b)
{
    if(b==0) return a;
    return gcd(b, a%b);
}

int lcm(int a, int b)
{
    return a/gcd(a, b)*b;
}

LL dfs(int pos, int sum, int prelcm, bool limit)
{
    if(pos == -1) return sum%prelcm==0;
    if(!limit && dp[pos][sum][index[prelcm]] != -1) return dp[pos][sum][index[prelcm]];
    int up = limit?a[pos]:9;
    LL ans = 0;
    for(int i=0; i<=up; ++i)
    {
        int newsum = (sum*10+i)%MOD;//2520为1~9的最小公倍数,数值对2520取余,如果该数(比2520大)能被其各位数整除,则它一定能被2520整除。
        int newlcm = prelcm;
        if(i)
            newlcm = lcm(newlcm, i);
        ans += dfs(pos-1, newsum, newlcm, limit&&(i==a[pos]));
    }
    if(!limit)
        dp[pos][sum][index[prelcm]] = ans;
    return ans;
}
LL solve(LL num)
{
    int len = 0;
    while(num)
    {
        a[len++] = num%10;
        num /= 10;
    }
    return dfs(len-1, 0, 1, true);
}
int main()
{
    LL n, m;
    int t;
    init();
    memset(dp, -1, sizeof(dp));
    scanf("%d",&t);
    while(t--)
    {
        scanf("%I64d%I64d",&n,&m);
        printf("%I64d\n",solve(m)-solve(n-1));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值