코딩캠프/BOJ
[9252] LCS2
by 코곰_
2024. 2. 23.
// 9252 LCS2
// dp
#include<iostream>
#include<cstdio>
#include<string.h>
#include<stack>
#define MAX 1001 // 최대 1000글자
using namespace std;
stack<char> stk;
int dp[MAX][MAX];
string a, b;
string ans = "";
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
// 배열 초기화
memset(dp, 0, sizeof(dp));
cin >> a;
cin >> b;
// dp
for(int i=1; i<=a.length(); i++){
for(int j=1; j<=b.length(); j++){
if(a[i-1] == b[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
}
else{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
int len = dp[a.length()][b.length()];
printf("%d\n", len);
int i = a.length();
int j = b.length();
while(dp[i][j] > 0){
if(dp[i][j] == dp[i][j-1]) j--;
else if(dp[i][j] == dp[i-1][j]) i--;
else{
stk.push(a[i-1]);
i--;
j--;
}
}
while(!stk.empty()){
printf("%c", stk.top());
stk.pop();
}
return 0;
}