这就是问题所在
给定两个序列,您需要找到并打印它们的最大公共子序列。
规格 输入 输入的第一行包含数字 N - 第一个序列的长度 (1 ≤ N ≤ 1000)。第二行包含第一个序列的成员(由空格分隔) - 模数不超过 10000 的整数。
第三行包含数字 M,即第二个序列的长度(1 ≤ M ≤ 1000)。第四行包含第二个序列的成员(用空格分隔) - 模数不超过 10000 的整数。
输出 要求显示这些序列的最大公共子序列,用空格分隔。
这是我尝试过的
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
using namespace std;
const int N = 1002;
int x[N], y[N], a[N][N];
int main() {
//ios_base::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
int n, m;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> x[i];
}
cin >> m;
for (int i = 1; i <= m; i++) {
cin >> y[i];
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (x[i] == y[j]) {
a[i][j] = 1 + a[i - 1][j - 1];
}
else {
a[i][j] = max(a[i - 1][j], a[i][j - 1]);
}
}
}
vector<int> v;
int i = n, j = m;
while (i && j) {
if (x[i - 1] == y[j - 1]) {
v.push_back(x[i]);
i--;
j--;
}
else if (a[i - 1][j] == a[i][j]) {
i--;
}
else {
j--;
}
}
for (int k = v.size() - 1; k >= 0; k--) {
cout << v[k] << ' ';
}
return 0;
}
首先:显示错误答案(例如,在以下输入数据 3 1 2 3 3 2 3 1 的情况下,它显示 3 而不是 2 3 )其次:它发出以下警告:

1 个回答