CF55D. 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 9 
output 

input 

12 15 
output 
2

题意:
  求一个区间内的Beautiful numbers有多少个。Beautiful numbers指:一个数能整除所有组成它的非0数字。 
  例如15可以被1和5整除,所以15是Beautiful numbers

思路:数位DP。
被每一位整除则用二进制记录已经包括的数字的个数,以及对2520取模后的状态。
由于对5整除当且仅当最后一个数为0或5,对2整除当且仅当最后一个数为偶数,且1~9的最小公倍数为2520,不包括2,5后的最小公倍数为252。
所以除最后一层对2520取模,其余时候都对252取模即可。
由于整除的状态有限,最多只有48个,于是我们预处理出这48个数,并来一个映射就好(不然会TLE)。

如果这篇难以理解 可以先看这道比较简单的题  https://blog.csdn.net/henucm/article/details/83272124

#include<cstdio>
#include<cmath>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<map>
#include<vector>
#define N 100005
#define ll long long
using namespace std;
ll a[5000];
ll dp[50][5000][50];
ll num[5000];
ll lcm(ll a,ll b)
{
	return a/__gcd(a,b)*b;
}
ll dfs(ll pos,ll persum,ll perlcm,ll flag)//pos 位数 persum 对2520取余后的数 perlcm 最小公倍数 flag 判断是否是第一位  为什么要判断? 
//  因为 例如 2340 当第一位取2时 第二位就只能取3以下的了  如果第一位取1时 第二位就可以取 0~9 的任意一个数了 
{
	if(pos==0)
	{
		return persum%perlcm==0;//如果是最后一位 判断 符合条件(persum%perlcm==0) 
	}
	if(!flag&&dp[pos][persum][num[perlcm]]!=-1) 
	return dp[pos][persum][num[perlcm]];
	int end=flag?a[pos]:9;
	ll ans=0;
	for(int i=0;i<=end;i++)
	{
		ll nowsum=(persum*10+i)%2520;
		ll nowlcm=perlcm;
		if(i)
		nowlcm=lcm(perlcm,i);
		ans+=dfs(pos-1,nowsum,nowlcm,flag&&i==end);
	}
	if(!flag)
	dp[pos][persum][num[perlcm]]=ans;
	return ans;
}
void init()//离散 
{
	int len=0;
	for(int i=1;i<=2520;i++)
	{
		if(2520%i==0)
		num[i]=++len;
	}
}
ll solve(ll x)
{
	int len=0;
	while(x)
	{
		a[++len]=x%10;
		x/=10;
	}
	return dfs(len,0,1,1);
}
int main()
{
	int t;
	cin>>t;
	init();
	memset(dp,-1,sizeof(dp));
	while(t--)
	{
		ll r,l;
		cin>>l>>r;
		cout<<solve(r)-solve(l-1)<<endl;
	}
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值