CodeForces - 55D Beautiful numbers

Discription

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

发现1-10的lcm是2520,并且从1-10中选出若干个数的lcm只有49种(都是搜出来的hhhh),于是我们可以直接数位dp,f[i][j][k][l]表示考虑了前i位,构成的数%2520==j,出现过的数的lcm是num[k],是否贴上界的情况是l的数的个数。
直接转移就好啦。

#include<bits/stdc++.h>
#define ll unsigned long long
using namespace std;
int T,a[23],n,num[105],N;
int to[105][10],v[23333];
ll L,R,f[23][2520][53][2];
int gcd(int x,int y){ return y?gcd(y,x%y):x;}
inline void init(){
	v[1]=v[0]=1;
	for(int i=2;i<10;i++)
	    for(int j=2520;j;j--) if(v[j]) v[j*i/gcd(j,i)]=1;
	for(int i=0;i<=2520;i++) if(v[i]) num[++N]=i,v[i]=N;

	for(int i=0;i<10;i++) to[1][i]=v[i];
	for(int i=2;i<=N;i++){
		to[i][0]=i;
	    for(int j=1;j<10;j++) to[i][j]=v[num[i]*j/gcd(num[i],j)];
	}
}

inline ll solve(ll x){
	memset(f,0,sizeof(f));
	n=0; while(x) a[++n]=x%10,x/=10;
	reverse(a+1,a+n+1);
	
	f[0][0][1][1]=1;
	for(int i=0;i<n;i++)
	    for(int j=0;j<2520;j++)
	        for(int k=1;k<=N;k++){
	        	if(!f[i][j][k][0]&&!f[i][j][k][1]) continue;
	            for(int u=0,now;u<10;u++){
	            	now=(j*10+u)%2520;
	            	f[i+1][now][to[k][u]][0]+=f[i][j][k][0];
	            	if(u<a[i+1]) f[i+1][now][to[k][u]][0]+=f[i][j][k][1];
	            	else if(u==a[i+1]) f[i+1][now][to[k][u]][1]+=f[i][j][k][1];
			    }
			}
	
	ll ans=0;
	for(int i=0;i<2520;i++)
	    for(int j=2;j<=N;j++) if(!(i%num[j])) ans+=f[n][i][j][0]+f[n][i][j][1];
	
	return ans;
}

int main(){
//	freopen("data.in","r",stdin); 
	init();
	scanf("%d",&T);
	while(T--) scanf("%I64u%I64u",&L,&R),printf("%I64u\n",solve(R)-solve(L-1));
	return 0;
}

  



猜你喜欢

转载自www.cnblogs.com/JYYHH/p/8932928.html