算法
- 状态表示:(f[i, j])
- 集合:所有由第一个序列的前 (i) 个字母和第二个序列前 (j) 个字母构成的,且以 (b[j]) 结尾的公共上升子序列
- 属性:Max
- 状态计算
- 所有包含 (a[i]) 的公共子序列: (f[i, k] + 1)
- 所有不包含 (a[i]) 的公共子序列: (f[i - 1, j])
暴力代码
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 3010;
int n;
int a[N], b[N], f[N][N];
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= n; ++i) cin >> b[i];
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (a[i] == b[j]) {
f[i][j] = max(f[i][j], 1);
for (int k = 1; k < j; ++k) {
if (b[k] < b[j]) f[i][j] = max(f[i][j], f[i][k] + 1);
}
}
}
}
int ans = 0;
for (int i = 1; i <= n; ++i) ans = max(ans, f[n][i]);
cout << ans << endl;
return 0;
}
优化代码
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 3010;
int n;
int a[N], b[N], f[N][N];
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= n; ++i) cin >> b[i];
for (int i = 1; i <= n; ++i) {
int maxv = 1;
for (int j = 1; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (a[i] == b[j]) f[i][j] = max(f[i][j], maxv);
if (a[i] > b[j]) maxv = max(f[i][j] + 1, maxv);
}
}
int ans = 0;
for (int i = 1; i <= n; ++i) ans = max(ans, f[n][i]);
cout << ans << endl;
return 0;
}