[数位DP+离散化] A - Beautiful numbers CodeForces - 55D

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

Copy

1
1 9

output

Copy

9

input

Copy

1
12 15

output

Copy

2

 

 

#include <bits/stdc++.h>
using namespace std;

int ch[30];
int gb[2530];
long long dp[20][2530][50];
//long long dp[20][2530][2530] 内存超限

void init()
{
	memset(dp, -1, sizeof dp);
	int num = 0;
	/// 离散化 2520为1-9的公倍数 2520是i的倍数 则i是1-9中几个数的公倍数
	for (int i = 1; i <= 2520; i++)
		if (2520 % i == 0)
		gb[i] = ++num;
	//cout<<num<<endl; 48
}

int gcd(int u, int v)
{
	return (v == 0) ? u : gcd(v, u % v);
} 

long long dfs(int pos, int mod, int gbs, bool lim)
{
	if (pos == 0)
		return mod % gbs == 0;

	if (!lim && dp[pos][mod][gb[gbs]] != -1)
		return dp[pos][mod][gb[gbs]];

	long long res = 0;
	int up = lim ? ch[pos] : 9;
	for (int i = 0; i <= up; i++)
		res += dfs(pos - 1, (mod * 10 + i) % 2520, i ? gbs * i  / gcd(gbs, i) : gbs, lim && (i == up));

	if (!lim)
		dp[pos][mod][gb[gbs]] = res;
	return res;
}

long long solve(long long x)
{
	int w = 0;
	while (x)
	{
		ch[++w] = x % 10;
		x /= 10;
	}
	return dfs(w, 0, 1, 1);
}

int main()
{
	int t;
	scanf("%d", &t);
	init();
	while (t--)
	{
		long long a, b;
		scanf("%I64d %I64d", &a, &b);
		printf("%I64d\n", solve(b) - solve(a - 1));
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值