cf55D. Beautiful numbers(数位dp)

题意

题目链接

Sol

看到这种题就不难想到是数位dp了。

一个很显然的性质是一个数若能整除所有位数上的数,则一定能整除他们的lcm。

根据这个条件我们不难看出我们只需要记录每个数对所有数的lcm(也就是2520)取模的结果

那么(f[i][j][k])表示还有(i)个数要决策,之前的数模(2520)(j),之前的数的lcm为k的方案

第三维可以预处理

#include<bits/stdc++.h> 
#define Pair pair<int, int>
#define MP(x, y) make_pair(x, y)
#define fi first
#define se second
#define int long long 
#define LL long long 
#define Fin(x) {freopen(#x".in","r",stdin);}
#define Fout(x) {freopen(#x".out","w",stdout);}
using namespace std;
const int MAXN = 1e6 + 10;
const double eps = 1e-9;
template <typename A> inline LL sqr(A x){return 1ll * x * x;}
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int f[21][2533][233], lim[MAXN], l, r, tot;
map<int, int> id;
void Get(int p) {
	tot = 0;
	while(p) lim[++tot] = p % 10, p /= 10;
}
int gcd(int a, int b) {
	return !b ? a : gcd(b, a % b);
}
int lcm(int a, int b) {
	return a / gcd(a, b) * b;
}
int dfs(int x, int sum, int lm, int opt) {//剩下i位需要决策,之前的数在%2520的意义下,数位上的数的lcm为lm的方案书, 是否顶着上界 
	if((!opt) && (~f[x][sum][id[lm]])) return f[x][sum][id[lm]];
	if(!x) return sum % lm ? 0 : 1;
	int res = 0;
	for(int i = 0; i <= (opt ? lim[x] : 9); i++) {
		int nxt = dfs(x - 1, (sum * 10 + i) % 2520, i == 0 ? lm : lcm(lm, i), opt && (i == lim[x]));
		res += nxt;
	}
	if(!opt) f[x][sum][id[lm]] = res;
	return res;
}
int calc(int x) {
	Get(x);
	return dfs(tot, 0, 1, 1);
}
void solve() {
	l = read(); r = read();
	cout << calc(r) - calc(l - 1) << '
';
}
signed main() {
	for(int i = 1, cnt = 0; i <= 2520; i++)
		if(!(2520 % i)) 
			id[i] = ++cnt;
		
    memset(f, -1, sizeof(f));
 	for(int T = read(); T--; solve());   
    return 0;
}
原文地址:https://www.cnblogs.com/zwfymqz/p/10548430.html