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 (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 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
9
1 12 15
2
【题解】
大致题意:给你一个区间,求出这个区间内能被自身各个数位整除的数的个数。
数位dp,满足被所有位上的数字(!0)整除的数 其实就是满足被这些位数的lcm整除 ,
而所有0~9的数的全部lcm只有48个,最大2520,想到每个数都是1~9中某些数字的lcm 所以他们一定能整除2520
所以我们开数组的时候要有x%2520 和lcm[ai]两项 再加上位数一项 所以 数组应该开成
dp[位数][x%2520][lcm[ai]]; 但是这样20*2520*2520会爆,所以得再优化,前面说了,dp数组第三维代表当前位数的lcm,而所有数的lcm值一共才48个,所以我们可以用离散化方法处理一下,即:把所有的48个lcm值都找出来,按顺序编号,因为每个lcm值都是不一样的,所以其编号也是独一无二的,这样一来就可以用不同的编号来代表不同的lcm值,这样第三维数组就只用开50就够了,,大大节约了空间,就可以AC了。
下面附上代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef __int64 ll;
const int inf=1e9+7;
const int N=200009;
ll dp[30][2530][50];
ll num[30];
int vis[2530];
int a[50];
int lcm(int m,int n)
{
return m/__gcd(m,n)*n;
}
ll dfs(int pos,int mod,int llcm,bool flag)
{
if(pos<0) return mod%llcm==0;//如果位数小于0了就返回
if(!flag&&dp[pos][mod][vis[llcm]]!=-1) return dp[pos][mod][vis[llcm]];//如果各位数达到了最大值9 就返回
int ii= flag==0?9:num[pos];//第pos位没到最后一位 就赋值为9,否则就赋值为当前值。
int lcm0;
ll ans=0;
for(int i=0;i<=ii;++i)
{
if(!i) lcm0=llcm;
else lcm0=lcm(llcm,i);
ans+=dfs(pos-1,(mod*10+i)%2520,lcm0,flag&&(i==ii));
}
if(!flag) dp[pos][mod][vis[llcm]]=ans;
return ans;
}
ll solve(ll m)
{
int len=0;
while(m)
{
num[len++]=m%10;
m/=10;
}
return dfs(len-1,0,1,1);
}
void init()
{
memset(vis,0,sizeof(vis));
int m;
for(int i=0;i<(1<<9);++i)//状压来表示状态
{
m=1;
for(int j=1;j<=9;++j)
{
if(i&(1<<j))
m=lcm(m,j+1);//最小公倍数
}
vis[m]=1;//最小公倍数标记
}
int l=0;
for(int i=0;i<=2520;++i)
{
if(vis[i]) a[l]=i,vis[i]=l++;//离散化处理 如果直接开2520的话数组会爆
//而0~9的所有lcm只有48个,有点大材小用,所以离散化处理,把每个lcm值按顺序标记
//这样不同的标记就代表不同的lcm值,但是数组只用开48大小。
}
}
int main()
{
int t;
scanf("%d",&t);
init();
memset(dp,-1,sizeof(dp));
while(t--)
{
ll m,n;
scanf("%I64d%I64d",&m,&n);
printf("%I64d\n",solve(n)-solve(m-1));
}
return 0;
}