这是一篇树状数组优化 DP 的题解。
有显然 DP:设 表示只考虑前 个数,且第 个数一定被划分到了子序列中,且 是在这个子序列的奇数还是偶数位置的方案数。
转移可以枚举子序列中倒数第二个元素的位置:
直接做是 的。
考虑优化转移。若我们动态维护 ,那么转移可以优化成:
的转移就可以做到 了。但是 的转移不能。
像这种在全集中只删除一个数的转移可以考虑维护其前后缀。即我们令 (其中 是值域,取 )。那么:
这样也能做到 转移了。
现在的问题是如何快速维护 。前二者是极易的,而后者只是前者的前缀/后缀最大值,树状数组维护即可。
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int n, a[N], f[N][2];
struct BIT {
int tr[N];
void modify(int u, int x) {
for (int i = u; i <= 5e5; i += i & -i) tr[i] = max(tr[i], x);
}
int query(int u) {
int res = 0;
for (int i = u; i; i -= i & -i) res = max(res, tr[i]);
return res;
}
}T1, T2;
int mx[N];
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i <= n; ++ i ) cin >> a[i];
for (int i = 1; i <= n; ++ i ) {
f[i][0] = mx[a[i]] ? mx[a[i]] + 1 : 0;
f[i][1] = max(T1.query(a[i] - 1), T2.query(5e5 - a[i])) + 1;
mx[a[i]] = max(mx[a[i]], f[i][1]);
T1.modify(a[i], f[i][0]);
T2.modify(5e5 - a[i] + 1, f[i][0]);
}
int res = 0;
for (int i = 1; i <= n; ++ i ) res = max(res, f[i][0]);
cout << res;
return 0;
}