To solve this problem, we need to determine the number of ways to place k non-attacking rooks on an n x n grid. Non-attacking rooks mean no two rooks share the same row or column.
Approach
-
Key Insight: For k non-attacking rooks, each rook must be in a distinct row and column. This leads us to two main calculations:
- Choosing Rows: We need to choose k rows out of n, which can be done in C(n, k) ways (combination).
- Assigning Columns: For the chosen k rows, we need to assign distinct columns. This is a permutation problem, P(n, k) (permutation of n columns taken k at a time).
-
Mathematical Formulation:
- Combination: C(n, k) = n! / (k! * (n - k)!)
- Permutation: P(n, k) = n! / (n - k)!
- Total Ways: The product of these two values gives the total number of ways to place k non-attacking rooks.
-
Modulo Operation: Since the result can be large, we use modulo 1e9+7. We precompute factorials and their modular inverses using Fermat's Little Theorem for efficient calculations.
Solution Code
MOD = 10**9 + 7
n, k = map(int, input().split())
if k > n:
print(0)
else:
# Precompute factorials modulo MOD
fact = [1] * (n + 1)
for i in range(1, n + 1):
fact[i] = fact[i-1] * i % MOD
# Precompute inverse factorials modulo MOD using Fermat's Little Theorem
inv_fact = [1] * (n + 1)
inv_fact[n] = pow(fact[n], MOD - 2, MOD)
for i in range(n-1, -1, -1):
inv_fact[i] = inv_fact[i+1] * (i+1) % MOD
# Calculate combination C(n, k)
comb = fact[n] * inv_fact[k] % MOD
comb = comb * inv_fact[n - k] % MOD
# Calculate permutation P(n, k)
perm = fact[n] * inv_fact[n - k] % MOD
# Total ways
result = comb * perm % MOD
print(result)
Explanation
- Factorial Precomputation: We compute the factorial of all numbers up to n modulo MOD. This helps in quickly calculating combinations and permutations.
- Inverse Factorial: Using Fermat's Little Theorem, we compute the modular inverse of each factorial. This allows us to divide by factorials in modular arithmetic.
- Combination Calculation: Using the precomputed factorials and inverse factorials, we calculate C(n, k).
- Permutation Calculation: Similarly, we calculate P(n, k) using the factorials and inverse factorials.
- Result: The product of the combination and permutation gives the total number of ways to place k non-attacking rooks, modulo MOD.
This approach efficiently handles the problem constraints and provides the correct result using modular arithmetic to avoid overflow. The precomputation steps ensure that the solution is optimal even for larger values of n.


作者声明:本文包含人工智能生成内容。