51Nod 1006 最长公共子序列Lcs
作者:互联网
题目大意:
题解:
最长公共子序列模板题,设\(dp[i][j]\)为字符串\(A[1...i]\)与字符串\(B[1...j]\)的最长公共子序列长度,则状态转移方程为:
用\(pre\)数组记录上一个状态,通过递归输出最长公共子序列。
#include <iostream>
#include <string>
using namespace std;
int dp[1010][1010], pre[1010][1010];
string a, b;
void print(int i, int j) {
if (!i || !j) {
return;
}
if (pre[i][j] == 0) {
print(i - 1, j - 1);
cout << a[i];
} else if (pre[i][j] == 1) {
print(i - 1, j);
} else {
print(i, j - 1);
}
}
int main() {
cin >> a >> b;
int lena = a.length(), lenb = b.length();
a = ' ' + a;
b = ' ' + b;
for (int i = 1; i <= lena; ++i) {
for (int j = 1; j <= lenb; ++j) {
if (a[i] == b[j]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
pre[i][j] = 0;
} else {
if (dp[i - 1][j] >= dp[i][j - 1]) {
dp[i][j] = dp[i - 1][j];
pre[i][j] = 1;
} else {
dp[i][j] = dp[i][j - 1];
pre[i][j] = 2;
}
}
}
}
print(lena, lenb);
return 0;
}
标签:pre,Lcs,51Nod,int,序列,1006,1010,最长,dp 来源: https://www.cnblogs.com/IzumiSagiri/p/15059614.html