【动态规划】【数位DP】[Codeforces 55 D]Beautiful numbers
题目描述
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.
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
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 should contain t numbers — answers to the queries, one number per line — quantities of beautiful numbers in given intervals (from
样例输入
样例一
1
1 9
样例二
1
12 15
样例输出
样例一
9
样例二
2
题目解析
在做数位DP的同时我们可以发现如果我们另
我们可以发现方程虽然正确但是如果我们在存储j和p的同时,我们发现
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int LACM = 2520;
typedef long long LL;
const int MAXN = 18;
LL f[MAXN+2][2530][50][2];
int _pow[MAXN+2];
int num[MAXN+2], Len;
int vtoid[LACM+10], idtov[50], idcnt;
int Hash(int v){
if(vtoid[v])
return vtoid[v];
idtov[vtoid[v] = ++idcnt] = v;
return idcnt;
}
int _gcd(int a, int b){
int c;
while(b){
c = a % b;
a = b;
b = c;
}
return a;
}
LL dfs(int u, int y, int s, int k){
if(~f[u][y][s][k]) return f[u][y][s][k];
f[u][y][s][k] = 0;
if(u == 0){
if(idtov[s]) f[u][y][s][k] = int(y % idtov[s] == 0);
return f[u][y][s][k];
}
int up = k != 0?num[u]:9, ngcd;
int ss = idtov[s];
for(int i=0;i<=up;i++){
ngcd = ss == 0 ? i : (i==0?ss:(ss*i/_gcd(ss, i)));
if(k&&i==up)
f[u][y][s][k] += dfs(u-1, (y+((i*_pow[u-1])%LACM))%LACM, Hash(ngcd), 1);
else
f[u][y][s][k] += dfs(u-1, (y+((i*_pow[u-1])%LACM))%LACM, Hash(ngcd), 0);
}
return f[u][y][s][k];
}
LL solve(LL u){
memset(f, -1, sizeof f);
Len = 0;
while(u){
num[++Len] = u % 10;
u /= 10;
}
return dfs(Len, 0, Hash(0), 1);
}
int main(){
_pow[0] = 1;
for(int i=1;i<=18;i++)
_pow[i] = _pow[i-1]*10%LACM;
LL L, R;
int t;
scanf("%d", &t);
while(t--){
scanf("%I64d%I64d", &L, &R);
printf("%I64d\n", solve(R) - solve(L-1));
}
return 0;
}