AcWing 1084. 数字游戏 II 简单数位DP
原题链接
中等
作者:
皓首不倦
,
2020-07-28 02:30:04
,
所有人可见
,
阅读 604
def get_num(n, N):
if n == 0:
return 1
arr = []
val = n
while val:
arr.append(val % 10)
val //= 10
# 前i个位置填写数值,所有数值和mod N = mod_val且前前面所有数位都取最大值的标记为all_higher_max情况下,所有合法的数值的种数
from functools import lru_cache
@lru_cache(typed=False, maxsize=128000000)
def dp(i, mod_val, all_higher_max):
if i == 0:
up_bound = arr[i] if all_higher_max else 9
cnt = 0
for cur_val in range(0, up_bound+1):
if cur_val % N == mod_val:
cnt += 1
return cnt
else:
up_bound = arr[i] if all_higher_max else 9
ans = 0
for cur_val in range(0, up_bound+1):
new_mod_val = (mod_val - cur_val) % N
ans += dp(i-1, new_mod_val, all_higher_max and cur_val == arr[i])
return ans
return dp(len(arr)-1, 0, True)
while True:
try:
a, b, N = map(int, input().split())
print( get_num(b, N) - get_num(a-1, N) )
except:
break