출처 : 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;
}
'BOJ 백준 > Dynamic Programming' 카테고리의 다른 글
| 백준 11054 - 가장 긴 바이토닉 부분 수열 (0) | 2020.10.23 |
|---|---|
| 백준 11053 - 가장 긴 증가하는 부분 수열 (0) | 2020.10.23 |
| 백준 01912 - 연속합 (0) | 2020.10.23 |
| 백준 02579 - 계단 오르기 (0) | 2020.10.23 |
| 백준 01932 - 정수 삼각형 (0) | 2020.10.23 |
