P8277 [USACO22OPEN] Up Down Subsequence P 题解
首先,容易想到一个暴力状态
显然这题的正解为 DP(毕竟这是个最优性问题,也没有办法使用贪心),但是状态已经有
我们考虑一下该问题的弱化版:最长上升子序列。众所周知最长上升子序列的时间复杂度也只有
定义
#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
int a[N], n, dp[N];
char b[N];
struct Fen_wick {
int c[N];
inline void add(int x, int y) {
for (; x <= n; x += x & -x) c[x] = max(c[x], y);
}
inline int ask(int x, int v = 0) {
for (; x; x -= x & -x) v = max(v, c[x]);
return v;
}
} t1, t2;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%d", a + i);
scanf("%s", b + 1);
int ans = 0;
for (int i = 1; i <= n; ++i) {
dp[i] = max(t1.ask(a[i] - 1), t2.ask(n - a[i])) + 1;
if (dp[i] != n)
if (b[dp[i]] == 'U')
t1.add(a[i], dp[i]);
else
t2.add(n - a[i] + 1, dp[i]);
ans = max(ans, dp[i]);
}
cout << ans - 1;
}