To solve this problem, we need to determine the number of ways to tile a 2xN grid using 1x2 and 2x1 dominoes. This problem can be efficiently solved using the Fibonacci sequence, as the number of valid tilings for a 2xN grid corresponds to the (N+1)-th Fibonacci number.
Approach
The key insight here is recognizing that the number of ways to tile a 2xN grid with dominoes follows the Fibonacci sequence. Here's why:
- For a 2x1 grid, there is only one way to tile it (using a vertical domino).
- For a 2x2 grid, there are two ways (two vertical dominoes or two horizontal dominoes).
- For any N > 2, the number of ways to tile a 2xN grid is the sum of the ways to tile a 2x(N-1) grid (adding a vertical domino to the end) and the ways to tile a 2x(N-2) grid (adding two horizontal dominoes to the end).
This leads to the recurrence relation:
Fib(N+1) = Fib(N) + Fib(N-1)
where Fib(1) = Fib(2) = 1.
Solution Code
MOD = 10**9 + 7
n = int(input())
k = n + 1 # We need the (n+1)-th Fibonacci number
if k <= 2:
print(1)
else:
a, b = 1, 1
for _ in range(k - 2):
a, b = b, (a + b) % MOD
print(b)
Explanation
- Modulo Operation: We use
10^9 +7as the modulus to handle large numbers and prevent overflow. - Fibonacci Calculation:
- For N=1, the result is Fib(2) =1.
- For N=2, the result is Fib(3)=2.
- For N>2, we compute the Fibonacci sequence iteratively up to the (N+1)-th term. This iterative approach is efficient with a time complexity of O(N) and space complexity of O(1).
This solution efficiently computes the number of valid tilings for the given 2xN grid. The result is always within the required modulus, ensuring correctness for large values of N.


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