Codeforces 933 A. A Twisty Movement (dp)
Description
A dragon symbolizes wisdom, power and wealth. On Lunar New Year’s Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence
.Little Tommy is among them. He would like to choose an interval , then reverse so that the length of the longest non-decreasing subsequence of the new sequence is maximum.
A non-decreasing subsequence is a sequence of indices
, such that and . The length of the subsequence is .
Input
The first line contains an integer , denoting the length of the original sequence.
The second line contains
space-separated integers, describing the original sequence .
Output
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
Examples input
4
1 2 1 2
Examples output
4
題意
在一個只包含 的序列中,翻轉其中任意一個區間,求此時最大的 LIS 。
思路
正著倒著預處理出每一段的 LIS,分別記為
然後開始列舉,翻轉一個區間相當於減去這段區間的貢獻,然後加上其翻轉以後的
此時 LIS 為
AC 程式碼
#include<bits/stdc++.h>
#define IO ios::sync_with_stdio(false);\
cin.tie(0);\
cout.tie(0);
using namespace std;
typedef __int64 LL;
const int maxn = 2e3+10;
int n;
int a[maxn];
int L[maxn][maxn],R[maxn][maxn];
int main()
{
IO;
cin>>n;
for(int i=0; i<n; i++)
cin>>a[i];
for(int i=0; i<n; i++)
{
int dp1 = 0, dp2 = 0;
for(int j=i; j<n; j++)
{
if(a[j]==1)
++dp1;
else
dp2 = max(dp1,dp2) + 1;
L[i][j] = max(dp1,dp2);
}
dp1 = dp2 = 0;
for(int j=i; j<n; j++)
{
if(a[j]==2)
++dp1;
else
dp2 = max(dp1,dp2) + 1;
R[i][j] = max(dp1,dp2);
}
}
int ans = 0;
for(int i=0; i<n; i++)
for(int j=i; j<n; j++)
ans = max(ans,L[0][n-1] - L[i][j] + R[i][j]);
cout<<ans<<endl;
return 0;
}