求LCS及输出一种具体的LCS序列。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
int n, m, a[N], b[N], f[N][N];
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i ++) cin >> a[i];
for (int i = 1; i <= m; i ++) cin >> b[i];
for (int i = 1; i <= n; i ++)//求LCS
{
for (int j = 1; j <= m; j ++)
{
if (a[i] == b[j]) f[i][j] = f[i - 1][j - 1] + 1;
else f[i][j] = max(f[i - 1][j], f[i][j - 1]);
}
}
cout << f[n][m] << '\n';
vector<int> v;//输出一种具体的LCS序列
int x = n, y = m;
while (x && y)
{
if (a[x] == b[y])
{
v.push_back(a[x]);
x --, y --;
}
else if (f[x - 1][y] > f[x][y - 1]) x --;
else y --;
}
reverse(v.begin(), v.end());
for (const auto &i : v) cout << i << " ";
//for (int i = 0; i < v.size(); i ++) cout << v[i] << " ";
return 0;
}