#include <iostream>
#include <vector>
#include <string>
using namespace std;
//最长公共子序列
vector<vector<int> > getdp1(string str1, string str2) {
vector<vector<int> > dp(str1.length(), vector<int>(str2.length()));
if (str1.length() == 0 || str2.length() == 0)
return dp;
dp[0][0] = str1[0] == str2[0] ? 1 : 0;
for (int j = 1; j < str2.length(); j ++) // 为第一行赋值
dp[0][j] = max(dp[0][j - 1], str1[0] == str2[j] ? 1 : 0);
for (int i = 1; i < str1.length(); i ++) //为第一列赋值
dp[i][0] = max(dp[i - 1][0], str2[0] == str1[i] ? 1 : 0);
for (int i = 1; i < str1.length(); i ++) { //滚动求dp矩阵
for (int j = 1; j < str2.length(); j ++) {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
if (str1[i] == str2[j])
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
return dp;
}
string lcse(string str1, string str2) {
string res = "";
if (str1.length() == 0 || str2.length() == 0)
return res;
vector<vector<int> > dp = getdp1(str1, str2);
int m = str1.length() - 1;
int n = str2.length() - 1;
for (m, n; m >= 0 && n >= 0; ) {
if (m > 0 &&dp[m][n] == dp[m - 1][n])
m --;
else if (n > 0 && dp[m][n] == dp[m][n - 1])
n --;
else {
res = str1[m] + res;
m --;
n --;
}
}
return res;
}
int main()
{
string str1 = "1A2C3D4B56";
string str2 = "B1D23CA45B6A";
vector<vector<int> > dp = getdp1(str1, str2);
for (int i = 0; i < dp.size(); i ++) {
for (int j = 0; j < dp[0].size(); j ++)
cout<<dp[i][j]<<" ";
cout<<endl;
}
cout<<lcse(str1, str2)<<endl; //输出12C4B6
return 0;
}