# CF 55D 数位DP

158人阅读 评论(0)

### D. Beautiful numbers

time limit per test 4 seconds

memory limit per test 256 megabytes

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

### 思路：

dp[i][j][k]表示处理到第i位，这个数（包含第i位）对2520取余是j，所有位的lcm是k的数的个数。如果j对k取余等于0，则这些数是美丽数字。

k的范围是1~2520，这样会超内存，所以伴有离散化过程，所有情况的数位lcm也就48个。

#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
const int mod=2520; //1~9的lcm为2520
int gcd(int a,int b) {
if(b==0) return a;
return gcd(b,a%b);
}
int lcm(int a,int b) {
if(a==0) return b;
if(b==0) return a;
return a*b/gcd(a,b);
}
int index[2525];
int initIndex() {
int tmp = 0;
for(int i=1;i<=2520;i++)
if(2520%i==0) index[i] = tmp++;
}
long long dp[25][mod][50];
int bit[25];
long long dfs(int pos,int prenum,int prelcm,bool flag) { //flag为true的话表示当前位触顶了
if(pos==-1) return prenum%prelcm == 0;
if(!flag && dp[pos][prenum][index[prelcm]]!=-1) return dp[pos][prenum][index[prelcm]];
int e = flag?bit[pos]:9;
long long ans=0;
for(int i=0;i<=e;i++) {
ans += dfs(pos-1,(prenum*10+i)%mod,lcm(prelcm,i),flag&&i==e);
}
if(!flag) return dp[pos][prenum][index[prelcm]]=ans;
return ans;
}

long long solve(long long n) {
int pos=0;
while(n) {
bit[pos++] = n%10;
n/=10;
}
return dfs(pos-1,0,1,true);
}
int main() {
int T;
long long l,r;
initIndex();
memset(dp,-1,sizeof(dp));
cin>>T;
while(T--) {
cin>>l>>r;
cout<<solve(r)-solve(l-1)<<endl;
}
}

0
0

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