728x90
https://www.acmicpc.net/problem/9252
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string s1, s2;
cin >> s1 >> s2;
vector<vector<int>> dp(s1.size() + 1, vector<int>(s2.size() + 1));
for (int i = 0; i <= s1.size(); i++) {
dp[i][0] = 0;
}
for (int i = 0; i <= s2.size(); i++) {
dp[0][i] = 0;
}
for (int i = 1; i <= s1.size(); i++) {
for (int j = 1; j <= s2.size(); j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
/*cout << " ";
for (int i = 0; i < s2.size(); i++) {
cout << s2[i] << " ";
}
cout << endl;
for (int i = 0; i <= s1.size(); i++) {
if (i != 0) {
cout << s1[i - 1] << " ";
}
else cout << " ";
for (int j = 0; j <= s2.size(); j++) {
cout << dp[i][j] << " ";
}
cout << endl;
}*/
cout << dp[s1.size()][s2.size()] << endl;
string result = "";
int nowRow = s1.size();
int nowCol = s2.size();
while (true) {
if (nowRow == 0 || nowCol == 0) break;
if (dp[nowRow][nowCol] != dp[nowRow - 1][nowCol] && dp[nowRow][nowCol] != dp[nowRow][nowCol - 1]) {
result += s1[nowRow - 1];
nowRow--;
nowCol--;
}
else if (dp[nowRow][nowCol] == dp[nowRow - 1][nowCol]) {
nowRow--;
}
else nowCol--;
}
for (int i = result.size() - 1; i >= 0; i--)
cout << result[i];
return 0;
}
728x90
'알고리즘 문제' 카테고리의 다른 글
[백준] 5337번 웰컴 (0) | 2020.03.01 |
---|---|
[백준] 1011번 Fly me to the Alpha Centauri (0) | 2020.03.01 |
[백준] 11055번 가장 큰 증가 부분 수열 (0) | 2020.02.29 |
[백준] 15969번 행복 (0) | 2020.02.29 |
[백준] 2475번 검증수 (0) | 2020.02.29 |