본문 바로가기
코딩캠프/BOJ

[9252] LCS2

by 코곰_ 2024. 2. 23.
// 9252 LCS2
// dp
#include<iostream>
#include<cstdio>
#include<string.h>
#include<stack>
#define MAX 1001 // 최대 1000글자  
using namespace std;

stack<char> stk;
int dp[MAX][MAX];

string a, b;
string ans = "";

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	
	// 배열 초기화 
	memset(dp, 0, sizeof(dp));
	
	cin >> a;
	cin >> b;

	// dp 
    for(int i=1; i<=a.length(); i++){
    	for(int j=1; j<=b.length(); j++){
    		if(a[i-1] == b[j-1]){
    			dp[i][j] = dp[i-1][j-1] + 1;
			}
			else{
				dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
			}
		}
	}
  
    int len = dp[a.length()][b.length()];
	printf("%d\n", len);

    
    int i = a.length();
    int j = b.length();
    while(dp[i][j] > 0){
    	if(dp[i][j] == dp[i][j-1]) j--;
    	else if(dp[i][j] == dp[i-1][j]) i--;
    	else{
    		stk.push(a[i-1]);
    		i--;
    		j--;
		}
	}

	while(!stk.empty()){
		printf("%c", stk.top());
		stk.pop();
	}
    
	return 0;
}

'코딩캠프 > BOJ' 카테고리의 다른 글

[2098] 외판원 순회  (0) 2024.02.23
[5582] 공통 부분 문자열  (0) 2024.02.23
[11660] 구간 합 구하기 5  (1) 2024.02.22
[14002] 가장 긴 증가하는 부분수열4  (0) 2024.02.22
[1932] 정수 삼각형  (1) 2024.02.22