1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | #include <stdio.h> #include <string> #include <iostream> #include <algorithm> #include <stack> using namespace std; string str1, str2; int dp[1005][1005] = { 0 }; stack<int> rst; int main() { cin >> str1 >> str2; int len1 = str1.size(); // i int len2 = str2.size(); // j str1 = "0" + str1; str2 = "0" + str2; for (int i = 1; i <= len2; i++) { if (str2[i] == str1[1]) { dp[1][i] = 1; for (int j = i; j <= len2; j++) { dp[1][j] = 1; } } } for (int i = 2; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1[i] == str2[j]) { dp[i][j] = dp[i-1][j-1] + 1; } else { dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } } printf("%d\n", dp[len1][len2]); int tmp = dp[len1][len2]; int idx = len2; for (int i = len1; i >= 1; i--) { if (tmp == 0) break; for (int j = idx; j >= 1; j--) { if (dp[i][j] == tmp && dp[i][j-1]!=tmp) { while (dp[i][j] == tmp) { i--; } i++; rst.push(j); tmp -= 1; idx = j-1; break; } } } while (rst.empty()==false) { int idx = rst.top(); rst.pop(); printf("%c", str2[idx]); } } | cs |
'알고리즘 > DP' 카테고리의 다른 글
5582 공통부분 문자열 (0) | 2019.07.13 |
---|---|
3943 헤일스톤 수열 (0) | 2019.07.12 |
2229 조짜기 (0) | 2019.07.12 |
2602 돌다리 건너기 (0) | 2019.07.12 |
2352 반도체 설계 (0) | 2019.07.11 |