To solve this problem, we need to determine the number of ways to tile a 3xN grid using 2x1 dominoes. This is a classic dynamic programming problem where we use a recurrence relation to efficiently compute the result.
Approach
-
Key Observations:
- A 3xN grid can only be tiled if N is even (since 3 is odd, an odd N would leave an uncovered cell).
- The number of ways to tile a 3xN grid (for even N) follows the recurrence relation:
dp[n] = 4 * dp[n-2] - dp[n-4](modulo (10^9 + 7))
- Base cases:
dp[0] = 1(empty grid has one way to be tiled)dp[2] = 3(3 ways to tile a 3x2 grid)
-
Dynamic Programming:
- For even N, compute the result using the recurrence relation. Avoid negative values by adding the modulus before taking the final modulo.
Solution Code
MOD = 10**9 + 7
N = int(input())
if N % 2 != 0:
print(0)
else:
if N == 0:
print(1)
elif N == 2:
print(3)
else:
prev_prev = 1 # dp[0]
prev = 3 # dp[2]
current = 0
for i in range(4, N + 1, 2):
current = (4 * prev - prev_prev) % MOD
if current < 0:
current += MOD
prev_prev = prev
prev = current
print(prev)
Explanation
- Odd N: If N is odd, output 0 since it's impossible to tile the grid.
- Even N:
- For N=0 (empty grid), output 1.
- For N=2, output the base case value of 3.
- For larger even N, compute the result using the recurrence relation. We maintain two previous values (
prev_prevfordp[n-4]andprevfordp[n-2]) to avoid storing the entire array, making the solution space-efficient.
This approach runs in O(N) time, which is efficient for the given constraints. The space complexity is O(1) since we only use a few variables to store the previous results.
Example Outputs:
- N=2 → 3
- N=4 →11
- N=6 →41
- N=1 →0
- N=3 →0
All these examples are correctly handled by the code. The solution is optimal and works for large values of N up to (10^6).


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