LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다.
예를 들어, ACAYKP와 CAPCAK의 LCS는 ACAK가 된다.
첫째 줄과 둘째 줄에 두 문자열이 주어진다. 문자열은 알파벳 대문자로만 이루어져 있으며, 최대 1000글자로 이루어져 있다.
첫째 줄에 입력으로 주어진 두 문자열의 LCS의 길이를, 둘째 줄에 LCS를 출력한다.
LCS가 여러 가지인 경우에는 아무거나 출력하고, LCS의 길이가 0인 경우에는 둘째 줄을 출력하지 않는다.
C++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
#define ioboost ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
string s1, s2, ans;
int dp[1001][1001];
void Input()
{
cin >> s1 >> s2;
}
void Solve()
{
int a = s1.length();
int b = s2.length();
for (int i = 1; i <= b; ++i)
{
for (int j = 1; j <= a; ++j)
{
if (s1[j - 1] == s2[i - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
//백트래킹
int col = a;
int row = b;
while (dp[row][col]) {
if (dp[row][col] == dp[row - 1][col]) {
row--;
}
else if (dp[row][col] == dp[row][col - 1]) {
col--;
}
else {
ans += s1[col - 1]; // DP 테이블에 0이 포함되어 있기 때문에 -1
row--; col--;
}
}
cout << dp[b][a] << '\n';
if (dp[b][a])
{
reverse(ans.begin(), ans.end());
cout << ans << '\n';
}
}
int main()
{
ioboost;
Input();
Solve();
return 0;
}