cf 461 div2.C. A Twisty Movement

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 is4.

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.因为序列只有1,2构成,所以我们可以找到最长不降子序列中第一个2出现的位置pos。

2.我们先处理出“1”的前缀和与“2”的后缀和,然后我们每次枚举位置pos,然后再依次枚举区间的l和r。

3.然后分别移动l,r的值,计算其对最长不降子序列贡献的最大值。

4.对于l,计算[1,l-1]中1的个数和[l,pos]中2的个数和的最大值。

5.对于r,计算[r,n]中2的个数和[pos,r-1]中1的个数和的最大值。


代码如下

#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);
}

猜你喜欢

转载自blog.csdn.net/acm513828825/article/details/79467850