* Computer Science/Algorithm

baekjun 9252. LCS2

soicem 2018. 8. 20. 14:46

 Longest Common Sequence 메트릭스를 만들고 역으로 올라가서 LCS 문자열을 구하는 문제


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
#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
int strBoard[1001][1001];
string s1;
string s2;
string getLCS(int i, int j) {
    if (strBoard[i][j] == 0)
        return "";
    while (strBoard[i][j] == strBoard[i - 1][j])
        i--;
    while (strBoard[i][j] == strBoard[i][j - 1])
        j--;
    return getLCS(i - 1, j - 1+ s1[i - 1];
}
 
int main() {
    cin >> s1 >> s2;
    int lenS1 = (signed)s1.size();
    int lenS2 = (signed)s2.size();
    for (int i = 1; i <= lenS1; i++
        for (int j = 1; j <= lenS2; j++
            if (s1[i - 1== s2[j - 1])
                strBoard[i][j] = strBoard[i - 1][j - 1+ 1;
            else if(s1[i - 1!= s2[j - 1])
                strBoard[i][j] = max(strBoard[i][j - 1], strBoard[i - 1][j]);
    
    cout << strBoard[lenS1][lenS2] << endl;
    cout << getLCS(lenS1, lenS2) << endl;
    //system("pause");
    return 0;
}
cs


'* Computer Science > Algorithm' 카테고리의 다른 글

baekjun 9012. 괄호  (0) 2018.08.22
baekjun 1874. 스택 순열  (0) 2018.08.22
baekjun 9461. 파도반수열  (0) 2018.08.14
baekjun 11066. 파일 합치기  (0) 2018.08.14
baekjun 9251. LCS(Longest Common Sequence)  (0) 2018.08.12