Codeforces-55D Beautiful numbers (数位DP)

来源:互联网 发布:农村淘宝加盟费 编辑:程序博客网 时间:2024/05/19 10:13

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
11 9
output
9
input
112 15
output
2
题目大意:统计区间[l,r]内中满足该数能被其所有非0位的数整除的数的个数?


想着前面做的加余数维的方法,想着弄成11维dp...但是时空都会超,然后就又不会了

数位DP果真太难了,状态好难想,貌似只有dfs有模版...


看了题解后了解到:如果一个数能整除a,b,...,z,则该数必定能整除他们的最小公倍数lcm

而1~9的最小公倍数为2520,且1~9中所有的可能的最小公倍数有48个,可以对最小公倍数离散化

所以可以设dp[25][50][2520],dp[i][ha[j]][k]表示长度为i时,且前面位的最小公倍数为j,且高位的数模MOD的值为k时,满足题意要求的答案

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MOD=2520;int n,len,bit[25];int ha[MOD];long long l,r;long long dp[25][50][MOD];//dp[i][ha[j]][k]表示长度为i时,且前面位的最小公倍数为j,且高位的数模MOD的值为k时,满足题意要求的答案long long LCM(int x,int y) {    return x/__gcd(x,y)*y;}long long dfs(int pos,int lcm,int rem,bool limit) {//pos表示当前考虑的位,lcm表示前面所有位的最小公倍数,rem表示前面数模MOD的值,limit表示当前位的值是否能随意取    if(pos<=0) {        return rem%lcm==0?1:0;    }    if(!limit&&dp[pos][ha[lcm]][rem]!=-1) {        return dp[pos][ha[lcm]][rem];    }    int mx=limit?bit[pos]:9;    long long res=0;    for(int i=0;i<=mx;++i) {        res+=dfs(pos-1,i==0?lcm:LCM(lcm,i),(rem*10+i)%MOD,limit&&i==mx);    }    if(!limit&&dp[pos][ha[lcm]][rem]==-1) {        dp[pos][ha[lcm]][rem]=res;    }    return res;}long long getCnt(long long x) {//返回[1,x]中满足题意的数的答案    len=0;    while(x>0) {        bit[++len]=x%10;        x/=10;    }    bit[len+1]=-1;    return dfs(len,1,0,true);}void init() {    for(int i=1,cnt=0;i<=MOD;++i) {        if(MOD%i==0) {            ha[i]=cnt++;        }    }    memset(dp,-1,sizeof(dp));}int main() {    int T;    init();    scanf("%d",&T);    while(T-->0) {        scanf("%lld%lld",&l,&r);        printf("%lld\n",getCnt(r)-getCnt(l-1));    }    return 0;}


0 0