HelloMinchan
처음처럼
HelloMinchan
LinkedIn
전체 방문자
오늘
어제
  • 분류 전체보기 (306)
    • Backend (4)
      • NestJS (1)
      • Express (1)
      • Spring (2)
    • Infrastructure (1)
      • AWS (1)
    • Frontend (1)
      • Next.js (1)
    • Language & Runtime (4)
      • Java (2)
      • Node.js (2)
    • Computer Science (8)
      • Computer Networks (3)
      • Operating Systems (4)
      • OOP (1)
    • 독서 (4)
      • 데이터 중심 애플리케이션 설계 (3)
      • 객체지향의 사실과 오해 (1)
    • 회고 (4)
      • Project (2)
      • Career (2)
    • Deprecated (280)

채널

  • GitHub
  • LinkedIn

최근 글

태그

  • 개발자
  • Algospot
  • 프로그래머스Python
  • 코딩
  • front-end
  • 데이터베이스
  • 프로그래밍
  • Database
  • 백준Python
  • 프로그래머스C++
  • 프로그래머스
  • 백엔드
  • back-end
  • 백준C++
  • 백준Go
  • 알고스팟
  • 백준
  • Baekjoon Online Judge
  • programmers
  • 알고스팟Python

최근 댓글

인기 글

hELLO
HelloMinchan

처음처럼

[Baekjoon Online Judge] 백준 9252번 LCS 2(C++, Python)
Deprecated

[Baekjoon Online Judge] 백준 9252번 LCS 2(C++, Python)

2020. 4. 22. 12:52

© 2020 All Rights Reserved. 주식회사 스타트링크

[Baekjoon Online Judge] 백준 9252번 LCS 2

(C++, Python)

(글쓴날 : 2020.04.22)

 


* Baekjoon Online Judge, 백준 9252번 문제 C++, Python 언어 풀이입니다.

* 소스 코드의 저작권은 글쓴이에게 있습니다.


 

 

백준 9252번 LCS 2


1) 문제

문제 링크 : https://www.acmicpc.net/problem/9252

 

9252번: LCS 2

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

www.acmicpc.net


2) 풀이 과정

* 시간 복잡도 : O(nm)

 

최장 공통 부분 수열 LCS(Longest Common Subsequence)를 구하는 문제입니다.

단, 이전 문제는 LCS의 길이만 구했지만, 이번에는 LCS 자체도 구해 출력해야 합니다.

 

저의 경우, 동적 계획법을 적용하였으며, C++과 Python을 사용했습니다.

먼저, 이전 문제에서 LCS의 길이를 구할 때처럼, 2차원 테이블에 memoization을 해 놓은 뒤 LCS를 구할 수 있는 규칙을 찾아야 합니다.

정해인지는 모르겠지만, 제가 찾은 규칙은 테이블의 마지막 행부터 거꾸로 열을 탐색해가며 수열의 길이와 같은 인덱스 값이 있을 경우, 해당 인덱스의 문자를 스택에 저장하였고, 탐색이 끝난 후, 스택을 출력하여 LCS를 완성해 문제를 해결했습니다.


3) 코드

 

* C++ 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <vector>
#include <string>
 
using namespace std;
 
int memoization[1001][1001];
 
int main(void)
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
 
    string str1 = "";
    string str2 = "";
    cin >> str1;
    cin >> str2;
    str1 = "0" + str1;
    str2 = "0" + str2;
 
    int N = str2.size();
    int M = str1.size();
 
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
        {
            if (!i || !j)
                continue;
 
            if (str1[j] == str2[i])
                memoization[i][j] = memoization[i - 1][j - 1] + 1;
            else
            {
                if (memoization[i - 1][j] > memoization[i][j - 1])
                {
                    memoization[i][j] = memoization[i - 1][j];
                    continue;
                }
                memoization[i][j] = memoization[i][j - 1];
            }
        }
    }
 
    int lcsLength = memoization[N - 1][M - 1];
    vector<char> stack;
 
    for (int i = N - 1; i > 0; i--)
    {
        for (int j = 1; j < M; j++)
        {
            if (memoization[i][j] == lcsLength)
            {
                if (str1[j] == str2[i])
                {
                    stack.push_back(str1[j]);
                    lcsLength--;
                    break;
                }
            }
        }
    }
 
    lcsLength = memoization[N - 1][M - 1];
    cout << lcsLength << '\n';
    for (int i = 0; i < lcsLength; i++)
    {
        cout << stack.back();
        stack.pop_back();
    }
 
    return 0;
}

* Python 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import sys
input = sys.stdin.readline
 
str1 = "0" + input().rstrip()
str2 = "0" + input().rstrip()
 
N = len(str2)
M = len(str1)
memoization = [[0] * M for _ in range(N)]
 
for i in range(N):
    for j in range(M):
        if not i or not j:
            continue
 
        if str1[j] == str2[i]:
            memoization[i][j] = memoization[i - 1][j - 1] + 1
        else:
            if memoization[i - 1][j] > memoization[i][j - 1]:
                memoization[i][j] = memoization[i - 1][j]
            else:
                memoization[i][j] = memoization[i][j - 1]
 
lcsLength = memoization[-1][-1]
stack = []
 
for i in range(N - 1, 0, -1):
    for j in range(1, M):
        if memoization[i][j] == lcsLength:
            if str1[j] == str2[i]:
                stack.append(str1[j])
                lcsLength -= 1
                break
           
print(memoization[-1][-1])
print(*(stack.pop() for _ in range(len(stack))), sep="")

 

저작자표시 비영리 변경금지 (새창열림)

'Deprecated' 카테고리의 다른 글

[GraphQL] GraphQL이란 무엇인가?  (1) 2020.04.23
[Baekjoon Online Judge] 백준 11051번 이항 계수 2(C++, Python)  (0) 2020.04.22
[Baekjoon Online Judge] 백준 9251번 LCS(C++, Python)  (0) 2020.04.21
[Baekjoon Online Judge] 백준 12015번 가장 긴 증가하는 부분 수열 2(C++, Python)  (0) 2020.04.20
[Baekjoon Online Judge] 백준 1520번 내리막 길(C++, Python)  (0) 2020.04.20
    'Deprecated' 카테고리의 다른 글
    • [GraphQL] GraphQL이란 무엇인가?
    • [Baekjoon Online Judge] 백준 11051번 이항 계수 2(C++, Python)
    • [Baekjoon Online Judge] 백준 9251번 LCS(C++, Python)
    • [Baekjoon Online Judge] 백준 12015번 가장 긴 증가하는 부분 수열 2(C++, Python)
    HelloMinchan
    HelloMinchan
    Though you should not fear failure, You should do your very best to avoid it.

    티스토리툴바