题目描述
blablabla
记录最长子序列的个数和分别有哪些数
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int a[N], f[N], g[N];
int n;
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= n; ++i) {
f[i] = 1;//如果只有第i个数,这一个数
g[i] = i;
for (int j = 1; j <= i - 1; ++j) {
if (a[j] < a[i]) {
f[i] = max(f[i], f[j] + 1);
g[i] = j;//存储上一个数从哪里来
}
}
}
int k = 1;
for (int i = 1; i <= n; ++i) {
if (f[k] < f[i])
k = i;
}
cout << f[k] << endl;
for (int i = 0, len = f[k]; i < len; ++i) {
printf("%d ", f[k]);
k = g[k];
}
}
C++ 代码 仅计算最长上升子序列的个数
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int a[N], f[N];
int n;
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= n; ++i) {
f[i] = 1;//如果只有第i个数,这一个数
for (int j = 1; j <= i - 1; ++j) {
if (a[j] < a[i])
f[i] = max(f[i], f[j] + 1);
}
}
int res = -1e9;
for (int i = 1; i <= n; ++i)
res = max(res, f[i]);
cout << res << endl;
}