AcWing 1084. 数字游戏 II
原题链接
中等
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int , int> pii;
typedef pair<ll , ll> pll;
int a , b , n;
vector<int> v;
int dp[15][110][2];
int dfs(int pos , int sum , bool lm)
{
if(dp[pos][sum][lm] != -1) return dp[pos][sum][lm];
if(pos == v.size())
{
return (sum % n == 0) ? 1 : 0;
}
int ans = 0 , up = lm ? v[pos]: 9;
for(int i = 0 ; i <= up ; i ++)
{
ans += dfs(pos + 1 , sum + i , lm ? (i == up) : false);
}
dp[pos][sum][lm] = ans;
return ans;
}
int cnt(int num)
{
if(num == 0) return 1;
memset(dp , -1 ,sizeof(dp));
v.clear();
while(num)
{
v.push_back(num % 10);
num /= 10;
}
reverse(v.begin() , v.end());
return dfs(0 , 0 , true);
}
void solve()
{
while(cin >> a >> b >> n)
cout << cnt(b) - cnt(a - 1) <<'\n';
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}