Problem - 1159http://acm.hdu.edu.cn/showproblem.php?pid=1159
#include <iostream>
#include <string.h>
using namespace std;
const int N = 1024;
int dp[N][N] = {0};
string str1, str2;
int LCS() {
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= str1.length(); i++) {
for (int j = 1; j <= str2.length(); j++) {
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[str1.length()][str2.length()];
}
int main() {
while (cin >> str1 >> str2) {
cout << LCS() << endl;
}
return 0;
}
打印路径
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
const int N = 1024;
int dp[N][N] = {0};
string str1, str2;
void printPath() {
string path;
for (int i = str1.length(), j = str2.length(); i > 0 && j > 0; ) {
if (str1[i - 1] == str2[j - 1]) {
path += str1[i - 1];
i--;
j--;
} else if (dp[i][j] == dp[i - 1][j]) {
i--;
} else {
j--;
}
}
reverse(path.begin(), path.end());
cout << path << endl;
}
int LCS() {
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= str1.length(); i++) {
for (int j = 1; j <= str2.length(); j++) {
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[str1.length()][str2.length()];
}
int main() {
while (cin >> str1 >> str2) {
cout << LCS() << endl;
printPath();
}
return 0;
}