CodeForces - 55D Beautiful numbers (数位dp+一些离散化处理)

题目:

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

题目大意:求在一定范围内 数能够被其每位上的数字(除0以外)整除的数 的个数。

思路:数位dp。满足条件的数一定是其每位上数字的最小公倍数的倍数。因为1~9的最小公倍数是2520,所以可将每个数的大小做对2520取余处理。所以可以这样设dp[20][2520][2520],第一个代表当前位数,第二个代表当前的最小公倍数,第三个代表数的当前大小。但是显然这样设dp,数组会很大,无法编译。所以我们可以考虑离散化,因为1~9的公倍数只有48个,所以设

dp[20][50][2520],这样就可以了。

AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
int t;
ll l,r;
ll dp[20][50][2521];
int a[20],h[2521];
int len;
void er(ll x)
{
	len=0;
    while(x)
	{
	    a[++len]=x%10;
		x/=10;	
	}	
}
int gcd(int x,int y)
{
	return y==0?x:gcd(y,x%y);
}
int lcm(int a,int b)
{
	return a/gcd(a,b)*b;
}
ll dfs(int pos,int lc,int lsum,int limit)//lc代表最小公倍数,lsum代表当前总和 
{
    if(pos==0){
    	return lsum%lc==0;
	}	
	if(!limit&&dp[pos][h[lc]][lsum]!=-1) 
	{
		return dp[pos][h[lc]][lsum];
	}
	ll ans=0;
	int cnt=limit?a[pos]:9;
	int i,j;
	int sum1,c;
	for(i=0;i<=cnt;i++)
	{
		sum1=(lsum*10+i)%2520;//更新 
		c=lc;
		if(i!=0)
		{
		 	c=lcm(lc,i);
		}
		ans+=dfs(pos-1,c,sum1,limit&&i==a[pos]);
	} 
	if(!limit)
	{
		dp[pos][h[lc]][lsum]=ans;
	}
	return ans;
} 
ll solve(ll x)
{
	er(x);
	ll ans=0;
	ans+=dfs(len,1,0,1);
	return ans;
}
int main()
{
	cin>>t;
	int i,j;
	for(i=1,j=1;i<=2520;i++)
	    if(2520%i==0)
	        h[i]=j++;	//对最小公倍数进行离散化 
	memset(dp,-1,sizeof(dp));//可以只初始化一次,因为对于具体的数是一定的,下一次可直接用 
	while(t--)
	{
		scanf("%I64d%I64d",&l,&r);
		ll val=solve(r)-solve(l-1);
		printf("%I64d\n",val);
	}
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值