[BOJ] 9251. LCS

SuLee·2022년 6월 21일
0

BOJ

목록 보기
49/67

9251. LCS

1. 문제

LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다.

예를 들어, ACAYKP와 CAPCAK의 LCS는 ACAK가 된다.

2. 입력

첫째 줄과 둘째 줄에 두 문자열이 주어진다. 문자열은 알파벳 대문자로만 이루어져 있으며, 최대 1000글자로 이루어져 있다.

3. 출력

첫째 줄에 입력으로 주어진 두 문자열의 LCS의 길이를 출력한다.

4. 풀이

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;
int dp[1001][1001];

void input()
{
    cin >> s1 >> s2;
}

void Solve()
{
    for (int i = 1; i <= s1.length(); ++i)
    {
        for (int j = 1; j <= s2.length(); ++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 << dp[s1.length()][s2.length()] << '\n';
}


int main()
{
    ioboost;
    input();
    Solve();
    
    return 0;
}

0개의 댓글