题目链接:https://codeforces.com/problemset/problem/933/A
dp[l][r][k] = {l 到 r 末尾为k的最长不上升子序列长度} 完成这个遍历每个区间即可,前用1的个数前缀和,后用2的个数的前缀和,中间这个区间用max(dp[l][r][0], dp[l][r][1]) 表示反转。
ac代码:
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int mx = 2e3+100;
#define ll long long
int l1[mx], l2[mx], s[mx];
int n;
int dp[mx][mx][2];
int sum(int l, int r) {
return l1[l-1]+l2[n]-l2[r];
}
int main () {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &s[i]);
if (s[i] == 1) l1[i] = l1[i-1]+1, l2[i] = l2[i-1];
else l2[i] = l2[i-1]+1, l1[i] = l1[i-1];
}
for (int l = 1; l <= n; ++l) {
dp[l][l][s[l]&1] = 1;
for (int r = l+1; r <= n; ++r) {
if (s[r] == 2) {
dp[l][r][0] = dp[l][r-1][0]+1;
dp[l][r][1] = dp[l][r-1][1];
}
else {
dp[l][r][0] = dp[l][r-1][0];
dp[l][r][1] = max(dp[l][r-1][1], dp[l][r-1][0])+1;
}
}
}
int mxx = 0;
for (int l = 1; l <= n; ++l) {
for (int r = l; r <= n; ++r) {
mxx = max(mxx, sum(l, r)+max(dp[l][r][0],dp[l][r][1]));
}
}
printf("%d\n", mxx);
}