문제) 백준 - 동적 계획법(Dynamic Programming) - 2xn 타일링
-> www.acmicpc.net/problem/11726
11726번: 2×n 타일링
2×n 크기의 직사각형을 1×2, 2×1 타일로 채우는 방법의 수를 구하는 프로그램을 작성하시오. 아래 그림은 2×5 크기의 직사각형을 채운 한 가지 방법의 예이다.
www.acmicpc.net
점화식을 다음과 같이 작성할 수 있다.
f(n) = f(n - 1) + f(n - 2)
파이썬 소스 코드는 위 점화식을 이용해서 작성했고, C++에서는 기저 사례(n = 1, n =2)의 설정과 재귀를 통해 답을 계산한다.
파이썬 소스코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
n = int(sys.stdin.readline()) | |
dp = [0, 1, 2] | |
for i in range(3, n+1): | |
dp.append((dp[i-1] + dp[i-2]) % 10007) | |
print(dp[n]) |
C++ 소스코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
#define endl "\n" | |
using namespace std; | |
int cache[1001]; | |
int solve(int n) { | |
if (n == 1) return 1; | |
if (n == 2) return 2; | |
int& ret = cache[n]; | |
if (ret != -1) return ret; | |
return cache[n] = (solve(n - 1) % 10007 + solve(n - 2) % 10007) % 10007; | |
} | |
int main() { | |
ios::sync_with_stdio(false); | |
cin.tie(0); cout.tie(0); | |
memset(cache, -1, sizeof(cache)); | |
int n; cin >> n; | |
cout << solve(n) << endl; | |
return 0; | |
} |
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 1629번 - 곱셈 (C++) 문제 및 풀이 (0) | 2021.04.09 |
---|---|
[백준] 2217번 - 로프 (파이썬/C++) 문제 및 풀이 (0) | 2021.04.05 |
[백준] 1005번 - ACM Craft (파이썬) 문제 및 풀이 (0) | 2021.03.30 |
[백준] 9251번 - LCS (파이썬) (0) | 2021.03.29 |
[백준] 15917번 - 노솔브 방지문제야!! (C++) 문제 및 풀이 (0) | 2021.03.25 |
댓글