Beautiful Numbers
Beautiful Numbers
https://ac.nowcoder.com/acm/problem/17385
Beautiful Numbers
题目地址:
基本思路:
我们发现因为位数只有位,所以数位之和不会超过,
因此我们考虑枚举数位之和,那么对于每个确定的我们把问题转化为了,
数字能被整除,并且数位之和为的数的数量,
那么这样我们就能每次取模,去进行一个比较简单的数位了,
注意如果我们用记录,
还有位没有确定,当前数取模结果为,剩下部分数位和为,总数位和为的数的数量,
那么对于每次查询并不用去重新初始化,能大大降低复杂度。
参考代码:
#pragma GCC optimize(2) #pragma GCC optimize(3) #include <bits/stdc++.h> using namespace std; #define IO std::ios::sync_with_stdio(false); cin.tie(0) #define int long long #define SZ(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define rep(i, l, r) for (int i = l; i <= r; i++) #define per(i, l, r) for (int i = l; i >= r; i--) #define mset(s, _) memset(s, _, sizeof(s)) #define pb push_back #define pii pair <int, int> #define mp(a, b) make_pair(a, b) #define INF 0x3f3f3f3f inline int read() { int x = 0, neg = 1; char op = getchar(); while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); } while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); } return neg * x; } inline void print(int x) { if (x < 0) { putchar('-'); x = -x; } if (x >= 10) print(x / 10); putchar(x % 10 + '0'); } int a[15]; int memo[15][110][110][110]; int n; int dp(int pos,int sum,int num,int mod,bool flag) { if (pos == 0) return sum == 0 && num == 0; if (flag && memo[pos][sum][num][mod] != -1) return memo[pos][sum][num][mod]; int cnt = flag ? 9 : a[pos]; int ans = 0; for (int i = 0; i <= cnt; i++) { ans += dp(pos - 1, (sum * 10 % mod + i) % mod, num - i, mod, flag || i < cnt); } if (flag) memo[pos][sum][num][mod] = ans; return ans; } int calc(int x) { int pos = 0; while (x) { a[++pos] = x % 10; x /= 10; } int ans = 0; for (int i = 1; i <= 12 * 9; i++) { ans += dp(pos, 0, i, i, false); } return ans; } signed main() { IO; int t; cin >> t; mset(memo, -1); for (int cas = 1; cas <= t; cas++) { cin >> n; int ans = calc(n); cout << "Case " << cas << ": " << ans << '\n'; } return 0; }