51 lines
1.1 KiB
C++
51 lines
1.1 KiB
C++
#include <bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
|
|
int main()
|
|
{
|
|
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]);
|
|
}
|
|
}
|
|
}
|
|
|
|
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;
|
|
} |