题目链接:https://vjudge.net/problem/POJ-2250
题目大意:
给出n组case,每组case由两部分组成,分别包含若干个单词,都以“#”当结束标志,要求输出最长子序列。
#include <iostream>
#include <string>
using namespace std; string a[], b[], ans[];
int alen, blen, len, dp[][], num[][]; void LCSLength() {
memset(dp, , sizeof(dp));
memset(num, , sizeof(num));
for (int i = ; i <= alen; i++) {
for (int j = ; j <= blen; j++) {
if (a[i] == b[j]) {
dp[i][j] = dp[i - ][j - ] + ;
num[i][j] = ;
}
else if (dp[i - ][j] >= dp[i][j - ]) {
dp[i][j] = dp[i - ][j];
num[i][j] = ;
}
else {
dp[i][j] = dp[i][j - ];
num[i][j] = ;
}
}
}
} void LCS(int i, int j) { //注意打印路径的方法
if (i == || j == ) return;
if (num[i][j] == ) {
ans[len--] = a[i];
LCS(i - , j - );
}
else if (num[i][j] == ) LCS(i - , j);
else LCS(i, j - );
} int main() { //注意输入格式
string s;
while (cin >> s) { //由于题目要求输入直到文件结束,所以这里要这样写
alen = , blen = ;
a[++alen] = s;
while (cin >> s) {
if (s=="#") break;
a[++alen] = s;
}
while (cin >> s) {
if (s=="#") break;
b[++blen] = s;
}
LCSLength();
len = dp[alen][blen];
LCS(alen, blen);
cout << ans[];
for (int i = ; i <= dp[alen][blen]; i++) cout << " " << ans[i];
cout << endl;
}
return ;
}
2018-05-18