문졔) 백준 - 동적 계획법 (Dynamic Programming) - 괄호
-> https://www.acmicpc.net/problem/10422
10422번: 괄호
‘(‘, ‘)’ 문자로만 이루어진 문자열을 괄호 문자열이라 한다. 올바른 괄호 문자열이란 다음과 같이 정의된다. ()는 올바른 괄호 문자열이다. S가 올바른 괄호 문자열이라면, (S)도 올바른 괄호
www.acmicpc.net
괄호의 길이가 L인 올바른 문자열의 개수를 구하고자 할 때, L은 다음과 같이 구할 수 있다.

solve(n)를 길이가 n인 올바른 문자열의 개수라 하면, 위의 문자열에서는 solve(L) = ∑ {solve(i - 2) * solve(L - i)}임을 알 수 있다. 또한, solve(i - 2)를 구하기 위한 작은 부분 문제가 반복되므로 memoization을 이용하여 이 문제를 해결할 수 있다.
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
#define _CRT_SECURE_NO_WARNINGS | |
#include <bits/stdc++.h> | |
#define endl "\n" | |
#define ll long long | |
#define loop(i, n) for(int i = 0; i <n;++i) | |
#define INF 987654321 | |
#define MAX 5001 | |
#define MOD 1000000007 | |
using namespace std; | |
ll cache[MAX]; | |
ll solve(int L) { | |
if (L % 2 == 1) return 0; | |
if (L == 0 || L == 2) return 1; | |
ll& ret = cache[L]; | |
if (ret != -1) return ret; | |
ret = 0; | |
for (int i = 2; i <= L; i++) { | |
ret += (solve(i - 2) * solve(L - i)); | |
ret %= MOD; | |
} | |
return ret; | |
} | |
int main() { | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
int T; cin >> T; | |
memset(cache, -1, sizeof(cache)); | |
while (T--) { | |
int n; | |
cin >> n; | |
cout << solve(n) << endl; | |
} | |
return 0; | |
} |
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 1351번 - 무한 수열 (C++) 문제 및 풀이 (0) | 2021.07.06 |
---|---|
[백준] 18870번 - 좌표 압축 (C++) 문제 및 풀이 (0) | 2021.06.29 |
[백준] 14499번 - 주사위 굴리기 (C++) 문제 및 풀이 (0) | 2021.06.29 |
[백준] 1715번 - 카드 정렬하기 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
[백준] 11279번 - 최대 힙 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
댓글