feat: 添加欧拉788题“支配数字”组合解法
This commit is contained in:
2
solutions/0788.dominatingNambers/README.md
Normal file
2
solutions/0788.dominatingNambers/README.md
Normal file
@@ -0,0 +1,2 @@
|
||||
核心思想是n位数中,n/2个数是相同的数量。
|
||||
这就可以转化为一个组合的问题。由此延展成为解法。
|
||||
66
solutions/0788.dominatingNambers/euler_788.py
Normal file
66
solutions/0788.dominatingNambers/euler_788.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
A dominating number is a positive integer that has more than half of its digits equal.
|
||||
|
||||
For example, 2022is a dominating number because three of its four digits are equal to 2. But
|
||||
2021 is not a dominating number.
|
||||
|
||||
Let D(N) be how many dominating numbers are less than 10^N .
|
||||
For example, D(4)=603 and D(10)=21893256 .
|
||||
|
||||
Find D(2022). Give your answer modulo 1_000_000_007.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def timer(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
start_time = time.time()
|
||||
result = func(*args, **kwargs)
|
||||
end_time = time.time()
|
||||
elapsed_time = end_time - start_time
|
||||
print(f"{func.__name__} time: {elapsed_time:.6f} seconds")
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
@timer
|
||||
def solve(N: int = 2022, MOD: int = 10**9 + 7):
|
||||
# 预处理阶乘和逆阶乘到 N+1
|
||||
fact = [1] * (N + 2)
|
||||
for i in range(1, N + 2):
|
||||
fact[i] = fact[i - 1] * i % MOD
|
||||
|
||||
inv_fact = [1] * (N + 2)
|
||||
inv_fact[N + 1] = pow(fact[N + 1], MOD - 2, MOD)
|
||||
for i in range(N, -1, -1):
|
||||
inv_fact[i] = inv_fact[i + 1] * (i + 1) % MOD
|
||||
|
||||
# 组合数函数
|
||||
def C(n: int, k: int) -> int:
|
||||
if k < 0 or k > n:
|
||||
return 0
|
||||
return fact[n] * inv_fact[k] % MOD * inv_fact[n - k] % MOD
|
||||
|
||||
# 预处理 9 的幂(到 N+2 足够)
|
||||
pow9 = [1] * (N + 3)
|
||||
for i in range(1, N + 3):
|
||||
pow9[i] = pow9[i - 1] * 9 % MOD
|
||||
|
||||
ans = 0
|
||||
K_max = (N - 1) // 2
|
||||
for k in range(0, K_max + 1):
|
||||
term = pow9[k + 1] * (C(N + 1, k + 1) - C(2 * k + 1, k + 1)) % MOD
|
||||
ans = (ans + term) % MOD
|
||||
return ans
|
||||
|
||||
|
||||
def main():
|
||||
n = int(input("N:"))
|
||||
mod = int(input("mod:") or (10**9 + 7))
|
||||
print(solve(n, mod))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user