【动态规划】【数位DP】[Codeforces 55 D]Beautiful numbers

来源:互联网 发布:mac添加农历 编辑:程序博客网 时间:2024/06/05 06:52

题目描述

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.

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 (1liri91018).

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 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
1 9

样例二

1
12 15

样例输出

样例一

9

样例二

2

题目解析

在做数位DP的同时我们可以发现如果我们另f(i,j,p,k)表示为最终答案,那么我们有目标答案为f(Len,0,0,1)那么我们其中i表示当前枚举到第i位,j表示当前的数字是多少,p表示当前的数字的每一个位数的最小公因数,k表示当前数字以及之前的位数是否满足严格小于,如果k=0那么我们知道前面已经出现小于我们要求的范围的那么这个位数就可以随便填,但是如果k=1那么我们知道我们这个数值不能超过当前对应的位置,那么,回到题目
我们可以发现方程虽然正确但是如果我们在存储j和p的同时,我们发现jpj实在是很大那么我们就使用特殊的方法举个例子我们有n2但是这个时候n太大了那么我们可以等价于n%2p2那么同理我们有lcm{1,2,3,4,5,6,7,8,9}=2520那么jp=j%lcm{1,2,3,4,5,6,7,8,9}p好了,同时我们发现p的取值范围最多有49个那hash一下就好了,开始做吧

代码

#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>using namespace std;const int LACM = 2520;typedef long long LL;const int MAXN = 18;LL f[MAXN+2][2530][50][2];int _pow[MAXN+2];int num[MAXN+2], Len;int vtoid[LACM+10], idtov[50], idcnt;int Hash(int v){    if(vtoid[v])        return vtoid[v];    idtov[vtoid[v] = ++idcnt] = v;    return idcnt;}int _gcd(int a, int b){    int c;    while(b){        c = a % b;        a = b;        b = c;    }    return a;}LL dfs(int u, int y, int s, int k){    if(~f[u][y][s][k]) return f[u][y][s][k];    f[u][y][s][k] = 0;    if(u == 0){        if(idtov[s]) f[u][y][s][k] = int(y % idtov[s] == 0);        return f[u][y][s][k];    }    int up = k != 0?num[u]:9, ngcd;    int ss = idtov[s];    for(int i=0;i<=up;i++){        ngcd = ss == 0 ? i : (i==0?ss:(ss*i/_gcd(ss, i)));        if(k&&i==up)            f[u][y][s][k] += dfs(u-1, (y+((i*_pow[u-1])%LACM))%LACM, Hash(ngcd), 1);        else            f[u][y][s][k] += dfs(u-1, (y+((i*_pow[u-1])%LACM))%LACM, Hash(ngcd), 0);    }    return f[u][y][s][k];}LL solve(LL u){    memset(f, -1, sizeof f);    Len = 0;    while(u){        num[++Len] = u % 10;        u /= 10;    }    return dfs(Len, 0, Hash(0), 1);}int main(){    _pow[0] = 1;    for(int i=1;i<=18;i++)        _pow[i] = _pow[i-1]*10%LACM;    LL L, R;    int t;    scanf("%d", &t);    while(t--){        scanf("%I64d%I64d", &L, &R);        printf("%I64d\n", solve(R) - solve(L-1));    }    return 0;}
0 0