📚 문제
[BOJ C++] 백준 9252번: LCS 2
https://www.acmicpc.net/problem/9252

📝 입력 및 출력

🔎 문제 풀이
- LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 DP를 사용하여 해결할 수 있다. 이 LCS 2 문제는 앞서 해결했던 LCS의 길이를 구하는 문제에서 더 나아가 LCS 자체까지 찾아내는 문제이다. LCS는 LCS의 길이를 구하기 위해 만들었던 배열을 역추적하여 LCS를 구할 수 있다. 자세한 설명은 아래 링크를 참조하자.
- [이론] 최장 공통 부분 수열 (LCS, Longest Common Subsequence)
- [BOJ C++] 백준 9251번: LCS
⌨️ C++ 코드
더보기
#include <bits/stdc++.h>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string str1, str2;
cin >> str1 >> str2;
int len1 = str1.size(), len2 = str2.size();
vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1));
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (str1[i-1] == str2[j-1])
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
string lcs = "";
int idx1 = len1, idx2 = len2;
while (dp[idx1][idx2]) {
if (str1[idx1 - 1] == str2[idx2 - 1]) {
lcs = str1[idx1 - 1] + lcs;
idx1--, idx2--;
} else {
if (dp[idx1 - 1][idx2] > dp[idx1][idx2 - 1])
idx1--;
else
idx2--;
}
}
cout << dp[len1][len2] << '\n'<< lcs;
}
'백준 문제풀이' 카테고리의 다른 글
| [BOJ C++] 백준 5502번: 팰린드롬 (0) | 2025.10.01 |
|---|---|
| [BOJ C++] 백준 17218번: 비밀번호 만들기 (0) | 2025.10.01 |
| [BOJ C++] 백준 11056번: 두 부분 문자열 (0) | 2025.10.01 |
| [BOJ C++] 백준 5582번: 공통 부분 문자열 (0) | 2025.10.01 |
| [BOJ C++] 백준 9251번: LCS (0) | 2025.10.01 |