此题可通过打表找规律,在 dfs ,就 OK 了。
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1e5 + 5;
const int MOD = 1e9 + 7;
string s;
int digits[55], n;
ll comb[55][55];
int dp[55], tmp[55];
int count_digits[10];
ll ans;
int table[] = {0, 45, 615, 6570, 63657, 597600, 5689830, 56017680, 564676515, 706253855, 53001921, 116607642,
807754616, 555253686, 93648429, 358785453, 214810078, 642432049, 158594480, 599067452, 311948107,
103373398, 86116420, 524897403, 907977314, 138576683, 44283636, 241998094, 583822532, 537947530,
636674358, 585550280, 414900917, 756538572, 442412153, 703712200, 837470764, 311869987,
733194120, 596841112, 387537647, 769854984, 977490984, 112225690, 117109110, 439421821,
374895741, 471922812, 10030060, 835556902, 25251932
};
void dfs(int pos, int flag) {
if (pos == 0) {
int x = 0;
for (int i = 1; i <= 9; i++) {
if (count_digits[i] >= count_digits[x]) {
x = i;
}
}
ans += x;
return;
}
if (!flag) {
int ma = 0, N = pos;
for (int i = 0; i <= 9; i++) {
ma = max(ma, count_digits[i]);
N += count_digits[i];
}
for (int x = 1; x <= 9; x++) {
for (int y = 0; y <= pos; y++) {
if (count_digits[x] + y < ma) {
continue;
}
if ((count_digits[x] + y) * (x + 1) + (count_digits[x] + y - 1) * (9 - x) < N) {
continue;
}
fill(dp, dp + 1 + pos, 0);
dp[y] = comb[pos][y];
for (int i = 0; i <= 9; i++) {
if (i == x) {
continue;
}
fill(tmp, tmp + 1 + pos, 0);
bool flag = true;
for (int j = 0; j + y <= pos; j++) {
int de = j + count_digits[i] - (y + count_digits[x]);
if (de > 0 || (x < i && de == 0)) {
break;
}
for (int k = j; k <= pos; k++) {
tmp[k] = (tmp[k] + dp[k - j] * comb[pos - k + j][j]) % MOD;
}
}
swap(tmp, dp);
}
ans += (ll)x * dp[pos];
}
}
ans %= MOD;
return;
}
int ed = flag ? digits[pos] : 9;
for (int i = 0; i <= ed; i++) {
count_digits[i]++;
dfs(pos - 1, flag && i == ed);
count_digits[i]--;
}
}
int main() {
for (int i = 0; i <= 50; i++) {
comb[i][0] = 1;
for (int j = 1; j <= i; j++) {
comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % MOD;
}
}
int T;
cin >> T;
while (T--) {
ans = 0;
cin >> s;
n = s.size();
ans = table[n - 1];
for (int i = 1; i <= n; i++) {
digits[i] = s[n - i] - '0';
}
for (int i = 1; i <= digits[n]; i++) {
count_digits[i]++;
dfs(n - 1, i == digits[n]);
count_digits[i]--;
}
cout << ans << "\n";
}
return 0;
}