43 P10959 月之谜 题解
P10959 月之谜
题面
如果一个十进制数能够被它的各位数字之和整除,则称这个数为“月之数”。
给定整数 \(L\) 和 \(R\),你需要计算闭区间 \([L,R]\) 中有多少个“月之数”。
\(1 \le L,R < 2^{31}\)
题解
这道题坑到我了,让我对数位dp的理解更深一步
一开始我设的状态为 \(f(pos, sum)\) ,但是这个状态实际上是信息不足的
因为我们最后要求这个数字能被其数位和整除,所以我们必须区分开数位和相同的数字
例如:2 和 11 ,2 是满足条件的,而 11 是不满足条件的,如果直接按照上面的状态去设,会把 11 也当成月之数


所以我们要将最后的数也记到状态里,但是因为值域太大,所以我们再记一个最后的数位和用作取模
设 \(f(pos, sum, mod, rem)\)
集合:已经填好 \(pos + 1 \sim len\) 位,填好的数的和为 \(sum\) ,最后的数位和为 \(mod\) ,当前数模 \(mod\) 为 \(rem\) ,后面任意填
值:集合中的月之数个数
状态数为 \(O(9^7)\) 左右,能过
code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 12;
int a[N], f[N][90][90][90];
// f[pos][sum][mod][k]
// 集合:已经填好 pos + 1 ~ len 位,前面已经填好的数位和为 sum ,固定模数(最后的数位和)为 mod , 当前数模 mod 为 k
// 值:符合条件的数的个数
int dfs (int pos, int sum, int mod, int rem, bool limit) {
if (!pos) return sum == mod && !rem;
int &now = f[pos][sum][mod][rem];
if (!limit && ~now) return now;
int up = limit ? a[pos] : 9;
int res = 0;
for (int i = 0; i <= up; i ++) {
res += dfs (pos - 1, sum + i, mod, (rem * 10 + i) % mod, limit && (i == up));
}
if (!limit) now = res;
return res;
}
int solve (int x) {
int len = 0;
while (x) {
a[ ++ len] = x % 10;
x /= 10;
}
int res = 0;
for (int i = 1; i <= 88; i ++) {
res += dfs (len, 0, i, 0, 1);
}
return res;
}
int main () {
memset (f, -1, sizeof f);
int l, r;
while (cin >> l >> r) {
if (l > r) {
cout << 0 << endl;
continue;
}
cout << solve (r) - solve (l - 1) << endl;
}
return 0;
}

浙公网安备 33010602011771号