녕의 학습 기록

백준_9252 LCS 2 (DP) 본문

Algorithm/Algorithm 문제

백준_9252 LCS 2 (DP)

kjyyjk 2024. 4. 21. 00:36

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BJ_9252_LCS2 {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String s1 = br.readLine();
        String s2 = br.readLine();

        int[][] d = new int[s1.length() + 1][s2.length() + 1];

        int i, j;
        for (i = 1; i < s1.length() + 1; i++) {
            for (j = 1; j < s2.length() + 1; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) { //같으면
                    d[i][j] = d[i - 1][j - 1] + 1;
                } else {
                    d[i][j] = Math.max(d[i][j - 1], d[i - 1][j]); //다르면
                }
            }
        }

        System.out.println(new StringBuilder().append(d[s1.length()][s2.length()]));
        if (d[s1.length()][s2.length()] == 0) { //0이면 종료
            return;
        }

        StringBuilder sb = new StringBuilder();
        i = s1.length();
        j = s2.length();
        while (sb.length() != d[s1.length()][s2.length()]) {
            if (s1.charAt(i - 1) == s2.charAt(j - 1)) { //같으면 LCS 문자
                sb.append(s1.charAt(i - 1));
                i--;
                j--; //대각선 왼쪽 위로
            } else {
                if (d[i][j - 1] > d[i - 1][j]) {
                    j--;
                } else {
                    i--;
                }
            }
        }
        System.out.println(sb.reverse());
    }
}
 

9252번: LCS 2

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

www.acmicpc.net

 

'Algorithm > Algorithm 문제' 카테고리의 다른 글

백준_1328 고층 빌딩 (DP)  (0) 2024.04.21
백준_1915 가장 큰 정사각형 (DP)  (0) 2024.04.21
백준_13398 연속합 2 (DP)  (0) 2024.04.18
백준_10844 쉬운 계단 수 (DP)  (0) 2024.04.16
백준_11726 2xn 타일링 (DP)  (0) 2024.04.15