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).
Sample test(s)
input
1
1 9
output
9
input
1
12 15
output
2
就是被每一个数字的LCM整除。
1~9的LCM最大是2520,其实也只有48个。
然后dp[i][j][k]表示处理到数位i,该数对2520取模为j,各个数位的LCM为k
算法分析:
题意:
定义:一个数如果能够被它所有位上非零数字整除那么这个数就是Beautiful Numbers。
给一个区间[L,R][L,R],求这个区间Beautiful Numbers的个数。
分析:
一个数能被它的所有非零数位整除,则能被它们的最小公倍数整除.这样我们就是数位DP枚举数,求该数的最小公倍数和该数.
1.而1到9的最小公倍数为2520,数位DP时我们只需保存前面那些位的最小公倍数就可进行状态转移,到边界时就把所有位的lcm求出了,
2.如何求这个数,显然要记录值是不可能的,其实我们只需记录它对2520的模即可.
3.这样我们就可以设计出如下数位DP:dfs(pos,mod,lcm,limit),pos为当前位,mod为前面那些位对2520的模,lcm为前面那些数位的最小公倍数,limit标记前面那些位是否达到上限,这样一来dp数组就要开到19*2520*2520,明显超内存了,考虑到最小公倍数是离散的,1-2520中可能是最小公倍数的其实只有48个,经过离散化处理后,dp数组的最后一维可以降到48,这样就不会超了。
代码实现:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD=2520;//1~9的lcm为2520
int index[MOD+10];//记录1~9的最小公倍数
ll dp[30][MOD][50];
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
int LCM(int a,int b)
{
return a/gcd(a,b)*b;
}
void init()
{
int num=0;
for(int i=1;i<=MOD;i++)
if(MOD%i==0)
index[i]=num++;
}
int a[30];
ll dfs(int pos,int sta,int lcm,int limit)
{
if(pos==-1){
return sta%lcm==0;
}
if(!limit&&dp[pos][sta][index[lcm]]!=-1)
return dp[pos][sta][index[lcm]];
int up=limit?a[pos]:9;
ll tmp=0;
for(int i=0;i<=up;i++)
{
int t1=(sta*10+i)%MOD;
int t2=lcm;
if(i!=0)
t2=LCM(lcm,i);
tmp+=dfs(pos-1,t1,t2,limit&&i==up);
}
if(!limit)
dp[pos][sta][index[lcm]]=tmp;
return tmp;
}
ll solve(ll x)
{
int pos=0;
while(x)
{
a[pos++]=x%10;
x/=10;
}
return dfs(pos-1,0,true,true);
}
int main()
{
memset(dp,-1,sizeof(dp));
int T;
cin>>T;
init();
for(int i=1;i<=12;i++)
cout<<index[i]<<" ";
for(int i=1;i<=T;i++)
{
ll n,m;
scanf("%lld%lld",&n,&m);
printf("%lld\n",solve(m)-solve(n-1));
}
return 0;
}