본문으로 바로가기

백준 09251 - LCS

category BOJ 백준Dynamic Programming 5년 전

출처 : www.acmicpc.net/problem/9251

 

9251번: LCS

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

www.acmicpc.net

 

고려사항

- LCS 알고리즘 공부하면 쉬움

- 메모제이션 초기값은 -1로 하자... ( www.acmicpc.net/board/view/49017 )

 

#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
string a, b;
int aLen, bLen;
int mat[1000][1000];
int lcs(int i, int j){
if(i < 0 || j < 0){
return 0;
}
int &v = mat[i][j];
if(v != -1){
return v;
}
if(a[i] == b[j]){
v = lcs(i-1, j-1) + 1;
}else{
v = max(lcs(i-1,j), lcs(i,j-1));
}
return v;
}
int main() {
cin>>a>>b;
aLen = a.length();
bLen = b.length();
memset(mat,-1,1000*1000*4);
cout<<lcs(aLen-1, bLen-1)<<"\n";
return 0;
}