[9251] LCS

Worldi·2022년 3월 7일
0

알고리즘

목록 보기
43/59

코드

#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int d[1001][1001];
int main(void)
{
    string a;
    string b;
    cin >> a >> b;
    for (int i = 0; i <= a.length(); i++)
    {
        for (int j = 0; j <= b.length(); j++)
        {
            d[i][j] = 0;
        }
    }
    for (int i = 0; i < a.length(); i++)
    {
        for (int j = 0; j < b.length(); j++)
        {

            //  cout << a[i] << " " << b[j] << "\n";
            if (a[i] == b[j])
            {
                d[i + 1][j + 1] = d[i][j] + 1;
            }
            else
            {
                d[i + 1][j + 1] = max(d[i][j + 1], d[i + 1][j]);
            }
        }
    }
    int max1 = d[1][1];
    for (int i = 0; i <= a.length(); i++)
    {
        for (int j = 0; j <= b.length(); j++)
        {
            if (max1 < d[i][j])
                max1 = d[i][j];
            //  cout << d[i][j] << " ";
        }
        //        cout << "\n";
    }
    cout << max1;
    return 0;
}

문제접근

다이나믹 프로그래밍으로 해결 할 수 있다.

해결 방법

기억 해야 할 것

두 문자열을 어떻게 비교해야 하나, 다이나믹 프로그래밍을 어떻게 적용해야하는지 잘 몰라서 참고하였다. 이차원 표를 작성하고, 이에 해당하는 규칙을 찾는 것이 관건인 것 같다.

profile
https://worldi.tistory.com/ 로 블로그 이전합니다.

0개의 댓글