C. A Twisty Movement
time limit per test 1 second
memory limit per test 256 megabytes
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, andhold the rods high and low to resemble a flying dragon.
A performerholding 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 a1, a2, ..., an.
Little Tommy isamong them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the newsequence is maximum.
A non-decreasingsubsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.
Input
The first linecontains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.
The second linecontains n space-separatedintegers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).
Output
Print a single integer, which means themaximum possible length of the longest non-decreasing subsequence of the newsequence.
Examples
Input
4
1 2 1 2
Output
4
Input
10
1 1 2 2 2 1 1 2 2 1
Output
9
Note
In the firstexample, after reversing [2, 3], the array willbecome [1, 1, 2, 2], where the lengthof the longest non-decreasing subsequence is 4.
In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9.
【题意】
给出长度为n的“1 2”序列,现在你可以选择任意一个区间[l,r]并将区间内的数逆序,问逆序序列最长不降子序列的最大长度。
【思路】
由于序列只由1和2组成,显然我们需要找到最长不降子序列中第一个2出现的位置pos,那么逆序后[l,pos)会使后面2的数目增加,(pos,r]会使前面1的数目增加。
PS:这里pos的含义就是我们前面的1全部选择,在pos及以后位置的2全部选择,[l,r]是我们要倒置的区间。
于是我们先处理出“1”的前缀个数和与“2”的后缀个数和,每次枚举前面提到的位置pos,再依次枚举区间的l和r。
然后分别滑动l,r的值,计算其对最长不降子序列贡献的最大值。
对于l,计算[1,l-1]中1的个数和[l,pos)中2的个数和的最大值。
对于2,计算[r,n]中2的个数和(pos,r-1]中1的个数和的最大值。
举个例子:
对于序列 1 2 2 1 1 2 1 2 2 2(假设下标从1开始)
我们枚举的位置为第六位,l=2,r=8.也就是我们会把区间[2,8]倒置,并以第6位为计数分界线,前面统计1的个数,后面统计2的个数,前面1的个数等于[1,l-1]原有序列中1的个数,和[pos+1,r]中2的个数,因为这部分被换到前面去了。统计2的个数同理。
当然这样换不是最优情况,只是说明方法,枚举pos和所有的l,r便可以得到最优解。
具体见代码。
#include <cstdio>
#include <cmath>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
#define mst(a,b) memset((a),(b),sizeof(a))
#define rush() int T;scanf("%d",&T);while(T--)
typedef long long ll;
const int maxn = 2005;
const ll mod = 1e9+7;
const ll INF = 1e18+5;
const double eps = 1e-9;
int n;
int a[maxn];
int pre1[maxn];
int pre2[maxn];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
pre1[i]=pre1[i-1]+(a[i]==1);
}
for(int i=n;i>=1;i--) pre2[i]=pre2[i+1]+(a[i]==2);
int ans=0;
for(int k=1;k<=n+1;k++) //枚举位置pos
{
int num1=0,num2=0;
for(int i=1;i<=k;i++) num1=max(num1,pre1[i-1]+pre2[i]-pre2[k]); //枚举l
for(int i=k;i<=n+1;i++) num2=max(num2,pre2[i]+pre1[i-1]-pre1[k-1]); //枚举r
ans=max(ans,num1+num2);
}
printf("%d\n",ans);
}