题目:
解析:
设\(f[pos][SumDigit][rem]\)为第\(pos\)位,各位数和为\(SumDigit\),当前余数为\(rem\)的数的个数
要求\(n\)可以被各位数整除,也就是\(n\%SumDigit==0\)
这个题,我们枚举一下各位数的和\(sum\)可能是多少,对每一个\(sum\)都记忆化搜索一下,看\(SumDigit==sum\)时有多少数满足条件,然后累加答案
代码:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5 + 10;
int l, r, num;
int digit[100], f[20][200][200];
int dfs(int pos, int rem, int sum, int SumDigit, int limit) {
if (pos == -1) return rem == 0 && sum == SumDigit;
if (!limit && f[pos][SumDigit][rem] != -1) return f[pos][SumDigit][rem];
if (SumDigit > sum) return 0;
int up = limit ? digit[pos] : 9, ans = 0;
for (int i = 0; i <= up; ++i)
ans += dfs(pos - 1, (rem * 10 + i) % sum, sum, SumDigit + i, limit && i == digit[pos]);
if (!limit) f[pos][SumDigit][rem] = ans;
return ans;
}
int solve(int x) {
num = 0;
int ret = 0;
while (x) {
digit[num++] = x % 10;
x /= 10;
}
for (int i = 1; i <= 9 * num; ++i) {
memset(f, -1, sizeof f);
ret += dfs(num - 1, 0, i, 0, 1);
}
return ret;
}
signed main() {
cin >> l >> r;
cout << solve(r) - solve(l - 1);
}