Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

9251: LCS #41

Open
minsoo0715 opened this issue Nov 21, 2023 · 0 comments
Open

9251: LCS #41

minsoo0715 opened this issue Nov 21, 2023 · 0 comments
Assignees
Labels
#다이나믹 프로그래밍 동적계획법 문제 @백준 백준(https://www.acmicpc.net) 문제 C/C++ c/c++로 해결한 문제들

Comments

@minsoo0715
Copy link
Owner

minsoo0715 commented Nov 21, 2023

9251: LCS

소스 코드

아이디어

  • dp[i][j]를 다음과 같이 정의한다.

    str1의 i번째 까지의 부분 문자열과 str2의 i번째 까지의 부분 문자열의 LCS(길이)

  • 두 문자열 ACAYKP, CAPCAK에 대해서 살펴보자

    • ACAYCAPCA
      ACAYCAPCA의 LCS는 ACA이고,
      ACAYKCAPC의 LCS는 AC이다.
      이때 A, K로 다른 문자이므로, 두 경우 중 더 길이가 긴 것이 ACAYK CAPCA의 LCS라고 할 수 있다.

    • ACAYKCAPCAK
      ACAYCAPCA의 LCS에 K를 추가하는 경우 이므로
      ACAY, CAPCA의 LCS에 K가 추가 된 문자열이 ACAYKCAPCAK의 LCS이다.

  • 따라서 LCS의 길이는 다음과 같이 정리할 수 있다. ( string은 0-based, dp 배열은 1-based)

    • str1[i-1] == str2[j-1]일때
      dp[i][j] = dp[i-1][j-1] + 1
    • 아닐때
      dp[i][j] = max(dp[i-1][j], dp[i][j-1])
* A C A Y K P
C 0 0 0 0 0 0
A 0 0 0 0 0 0
P 0 0 0 0 0 0
C 0 0 0 0 0 0
A 0 0 0 0 0 0
K 0 0 0 0 0 0

i = 1 일 때 (string idx = 0)

* A C A Y K P
C 0 1 1 1 1 1
A 0 0 0 0 0 0
P 0 0 0 0 0 0
C 0 0 0 0 0 0
A 0 0 0 0 0 0
K 0 0 0 0 0 0

반복

* A C A Y K P
C 0 1 1 1 1 1
A 1 1 2 2 2 2
P 1 1 2 2 2 3
C 1 2 2 2 2 3
A 2 2 3 3 3 3
K 2 2 3 3 4 4

구현

for(int i = 1; i<=l1; ++i) {
    for(int j = 1; j<=l2; ++j) {
        if(str1[i-1] == str2[j-1]) {
            dp[i][j] = dp[i-1][j-1] + 1;
        }else {
            dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
        }
    }
}
@minsoo0715 minsoo0715 added @백준 백준(https://www.acmicpc.net) 문제 C/C++ c/c++로 해결한 문제들 #다이나믹 프로그래밍 동적계획법 문제 작성예정 labels Nov 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
#다이나믹 프로그래밍 동적계획법 문제 @백준 백준(https://www.acmicpc.net) 문제 C/C++ c/c++로 해결한 문제들
Projects
None yet
Development

No branches or pull requests

1 participant