Digit Sum

Digit Sum

数位dp

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1e9 + 7;
const int N = 1e4 + 10;

string k; int d;
int n;
ll dp[N][2][100];

ll dfs(int pos, int tight, int rem) {
    if(pos == n) return (rem == 0 ? 1 : 0);
    if(dp[pos][tight][rem] != -1) return dp[pos][tight][rem];

    int cur = k[pos] - '0';
    int limit = tight ? cur : 9;

    ll res = 0;

    for(int i = 0; i <= limit; i ++) {
        int newtight = (i == limit && tight) ? 1 : 0;
        int newrem = (rem + i) % d;

        res += dfs(pos + 1, newtight, newrem);
        res %= MOD;
    }
    dp[pos][tight][rem] = res;
    return res;
}

void solve() {
    cin >> k >> d;
    n = k.size();
    memset(dp, -1, sizeof(dp));
    ll ans = dfs(0, 1, 0);

    cout << (ans - 1 + MOD) % MOD << "\n"; 
}

int main() {
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    int _ = 1; //cin >> _;
    while(_--) solve();
    return 0;
}
posted @ 2026-10-13 14:40  thenrify  阅读(5)  评论(0)    收藏  举报