백준 1958 c++ : DP, LCS

magicdrill·2025년 1월 15일

백준 문제풀이

목록 보기
529/673

백준 1958 c++ : DP, LCS

2개의 문자열에서 공통문자열을 찾는 LCS에서 확장된 3개의 문자열에서 공통문자열을 찾는다.
삼중반복문이 플로이드-워셜과 유사한거 같은데, 까먹기 전에 한번 더 해보겠다.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int find_answer(string A, string B, string C) {
	//cout << "find_answer()\n";
	
	int answer = 0;
	int A_length = A.length();
	int B_length = B.length();
	int C_length = C.length();
	int i, j, k;

	vector<vector<vector<int>>> DP(A_length + 1, vector<vector<int>>(B_length + 1, vector<int>(C_length + 1, 0)));
	for (i = 1; i <= A_length; i++) {
		for (j = 1; j <= B_length; j++) {
			for (k = 1; k <= C_length; k++) {
				if (A[i - 1] == B[j - 1] && B[j - 1] == C[k - 1]) {
					DP[i][j][k] = DP[i - 1][j - 1][k - 1] + 1;
				}
				else {
					DP[i][j][k] = max({ DP[i - 1][j][k], DP[i][j - 1][k], DP[i][j][k - 1] });
				}
			}
		}
	}
	answer = DP[A_length][B_length][C_length];

	return answer;
}

int main(void) {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	string A, B, C;
	cin >> A;
	cin >> B;
	cin >> C;
	cout << find_answer(A, B, C) << "\n";

	return 0;
}

0개의 댓글