난이도: 골드 5
문제 링크:www.acmicpc.net/problem/9251
9251번: LCS
LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다. 예를 들어, ACAYKP와 CAPCAK의 LCS는 ACAK가 된다.
www.acmicpc.net

이전 글 (링크)에서 소개한 LCS 알고리즘을 이용하여 푸는 문제입니다.
자세한 내용은 링크에 거의 그대로 설명이 되어 있습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <algorithm> | |
using namespace std; | |
#define MAX_N 1001 | |
int lcs[MAX_N][MAX_N]; | |
int main() { | |
string first, second; | |
cin >> first >> second; | |
int firl = first.length(); | |
int secl = second.length(); | |
lcs[0][0] = 0; | |
for (int i = 1; i <= firl; i++){ | |
lcs[i][0] = 0; | |
} | |
for (int i = 1; i <= secl; i++){ | |
lcs[0][i] = 0; | |
} | |
for (int i = 1; i <= firl; i++){ | |
for (int j = 1; j <= secl; j++) { | |
if (first[i-1] == second[j-1]) | |
lcs[i][j] = min(lcs[i-1][j-1], min(lcs[i-1][j], lcs[i][j-1]))+1; | |
else { | |
lcs[i][j] = max(lcs[i-1][j-1], max(lcs[i-1][j], lcs[i][j-1])); | |
} | |
} | |
} | |
cout << lcs[firl][secl]; | |
return 0; | |
} |
코드를 늘 직관적이고 읽기 쉽게 작성하려고 노력하고 있습니다.
혹시나 제 코드 중 의미 전달이 불명확한 경우가 있다면 피드백을 주시면 감사하겠습니다.
'알고리즘, 문제해결 > 알고리즘 문제풀이' 카테고리의 다른 글
[백준 5582번] 공통 부분 문자열 (0) | 2020.11.15 |
---|---|
[백준 9252번] LCS 2 (0) | 2020.11.15 |
[백준 17501번] 수식 트리 (0) | 2020.11.08 |
[백준 17498번] 폴짝 게임 (0) | 2020.11.07 |
[백준 17498번] 폴짝 게임 (시간 초과) - 실패 (0) | 2020.11.06 |
댓글