feat: updated LCS problem

This commit is contained in:
2025-12-09 21:26:27 -03:00
parent e75daedef5
commit 0951a11635
110 changed files with 201 additions and 30 deletions

View File

@@ -2,25 +2,50 @@
using namespace std;
int memo[1011][1011];
int solve(string &s1, string &s2, int i = 0, int j = 0)
int main()
{
if (i == s1.size() || j == s2.size()) return 0;
if (memo[i][j] != - 1) return memo[i][j];
if (s1[i] == s2[j]) {
return memo[i][j] = (solve(s1, s2, i + 1, j + 1) + 1);
int n, m;
cin >> n >> m;
string s1, s2;
cin >> s1 >> s2;
/*
let dp[i][j] represent the length of the longest common subsequence using the first i characters
of s1 and the first j characters of s2
if s1[i] == s2[j]
dp[i][j] = dp[i - 1][j - 1] + 1
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
*/
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1];
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return memo[i][j] = max(solve(s1, s2, i, j + 1), solve(s1, s2, i + 1, j));
}
int main(){
int n, m; cin >> n >> m;
string s1, s2; cin >> s1 >> s2;
memset(memo, -1, sizeof(memo));
cout << solve(s1, s2) << endl;
int row = n, col = m;
string sub = "";
while (dp[row][col]) {
if (s1[row - 1] == s2[col - 1]) {
sub = string(1, s1[row - 1]) + sub;
row--, col--;
} else if (dp[row - 1][col] > dp[row][col - 1]) {
row--;
} else {
col--;
}
}
int size = dp[n][m];
cout << size << endl;
cout << sub << endl;
return 0;
}