题目来源:http://codeforces.com/problemset/problem/55/D
一个数如果能够被它所有位上(非零数字!!!)整除那么这个数就是Beautiful Numbers。
给定一个区间询问这个区间内的完美数。
这道题目妙啊~~~~~。
我们先求出1-9数字的最小公倍数(LCM)(打个表即可),可求出来是2520,2520肯定能被实际的最小公倍数整除,即2520%(实际的最小公倍数)==0,在数位DP从高位到低位进行dfs时候,取每一位的对2520取余的结果res,以及所有实际位构成的最小公倍数hhlcm,最后一步判断res%hhlcm是否为0即可。
::2520=k*lcm是没有问题的,一定是它的倍数关系。
(x % (k * lcm))% lcm = 0
是否等价于x % lcm = 0 一定是
正确的,因为可以把x拆分成k*lcm+b,
b%lcm=(k*lcm+b)%lcm是相等的。
dp[i][j][k] 表示到第i位对2520取模后为j,各位的lcm为k的数字个数。
dp[pos][res][book[hhlcm]]表示到pos位时前面高位对2520取余为res和前面数字最小公倍数是hhlcm时的答案,book[hhlcm]离散化(也就是1-9数字任意个任意组合的最小公倍数)。
因为hhlcm按2520取值根本开不下,所以对hhlcm进行离散化,因为hhlcm一定可以整除2520,所以将1~2520可以整除2520的数进行标记即可,测试后发现只有48个,满足当前情况。
扫描二维码关注公众号,回复:
8780151 查看本文章
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<algorithm>
#include<queue>
#define MAX_len 50100*4
using namespace std;
typedef long long ll;
const ll mod=1000000007;
int a[70];
int book[2530]={0};
ll dp[25][2530][100];
int gcd(int a,int b)
{
return b==0? a:gcd(b,a%b);
}
ll dfs(int pos,int res,int hhlcm,bool limit)
{
if(pos<1)
{
if(res%hhlcm==0)
return 1;
return 0;
}
if(!limit&&dp[pos][res][book[hhlcm]]!=-1)
return dp[pos][res][book[hhlcm]];
int up=limit?a[pos]:9;
ll temp=0;
for(int i=0;i<=up;i++)
{
int t1=hhlcm;
if(i)
t1=i/gcd(t1,i)*hhlcm;
temp+=dfs(pos-1,(i+res*10)%2520,t1,limit&&i==up);
}
if(!limit)
dp[pos][res][book[hhlcm]]=temp;
return temp;
}
ll solve(ll n)
{
int len=1;
while(n)
{
a[len++]=n%10;
n/=10;
}
return dfs(len-1,0,1,true);
}
void init()
{
int i,j,k;
j=0;
for(i=1;i<=2520;i++)
{
if(2520%i==0)
book[i]=j++;
}
}
int main()
{
init();
memset(dp,-1,sizeof(dp));
int T;
scanf("%d",&T);
while(T--)
{
ll l,r;
scanf("%I64d %I64d",&l,&r);
printf("%I64d\n",solve(r)-solve(l-1));
}
return 0;
}