题意:两个人写了一些单词,要求得出一个单词集,单词集是两个人写的单词序列中的最长公共子序列。
题解:敲上最长公共子序列的模板代码后,还要递归打印出这些单词。
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
const int N = 105;
string str1[N], str2[N], res[N];
int f[N][N], n, n1, n2, path[N][N], flag;
void sub_print(int a, int b) {
if (a == 0 || b == 0)
return;
if (path[a][b] == 1) {
sub_print(a - 1, b - 1);
if (flag)
cout << " ";
flag = 1;
cout << str1[a];
}
else if (path[a][b] == 2)
sub_print(a - 1, b);
else
sub_print(a, b - 1);
}
int main() {
while (cin >> str1[1]) {
flag = 0;
n1 = 1;
while (str1[n1] != "#")
cin >> str1[++n1];
cin >> str2[1];
n2 = 1;
while (str2[n2] != "#")
cin >> str2[++n2];
memset(f, 0, sizeof(f));
n1--;
n2--;
for (int i = 1; i <= n1; i++)
for (int j = 1; j <= n2; j++)
if (str1[i] == str2[j]) {
f[i][j] = f[i - 1][j - 1] + 1;
path[i][j] = 1;
}
else {
f[i][j] = f[i - 1][j] > f[i][j - 1] ? f[i - 1][j] : f[i][j - 1];
if (f[i][j] == f[i - 1][j])
path[i][j] = 2;
else
path[i][j] = 3;
}
sub_print(n1, n2);
cout << endl;
}
return 0;
}