数位dp Beautiful numbers

69人阅读 评论(0)

Description
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).

Sample Input
Input
1
1 9
Output
9
Input
1
12 15
Output
2

ac代码：

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef long long ll;
#define mod 2520
ll dp[20][mod][50];
int tem[22];
int indx[mod+5];
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
ll LCM(ll a,ll b)
{
return a/gcd(a,b)*b;
}
ll dfs(int len,int pre,int lcm,bool fp)
{
if(!len)        //到了最后一位，如果pre%lcm==0，那么pre就是一个美丽数。
return pre%lcm==0;   //递归出口！
if(!fp && dp[len][pre][indx[lcm]]!=-1)  //如果当前状态没有上限，并且该状态已经遍历过。那么就直接返回。
return dp[len][pre][indx[lcm]];
int maxn=fp?tem[len]:9;  //有上限的话，当前位最多取到tem[len]，没有上限的话就可以取到9.
ll ans=0;
for(int i=0;i<=maxn;i++)       //遍历len位的数。
{
int nowsum,nowlcm=lcm;
nowsum=(pre*10+i)%mod;
if(i)
nowlcm=LCM(lcm,i);        //当前数的最小公倍数。
ans+=dfs(len-1,nowsum,nowlcm,fp && i==maxn);
}
if(!fp)
dp[len][pre][indx[lcm]]=ans;  //记忆化搜索。
return ans;
}
void init()  //这里主要是为了压缩空间。因为符合条件的i只有48个，所以可以将dp的第3维压缩到50.
{
int i;
int num=0;
for(i=1;i<=2520;i++)
{
if(mod%i==0)
indx[i]=++num;
}
memset(dp,-1,sizeof(dp));
}
ll cal(ll a)
{
int top=0;
while(a)
{
tem[++top]=a%10;
a=a/10;
}
return dfs(top,0,1,1);
}
int main()
{
int t;
ll a,b;
scanf("%d",&t);
init();
while(t--)
{
scanf("%I64d%I64d",&a,&b);
printf("%I64d\n",cal(b)-cal(a-1));
}
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：41867次
• 积分：1812
• 等级：
• 排名：千里之外
• 原创：164篇
• 转载：0篇
• 译文：0篇
• 评论：0条
评论排行