Codeforces 933 A. A Twisty Movement (dp)

本文探讨了在特定序列中通过翻转区间来最大化最长非递减排列子序列的问题,并提供了一种有效的算法解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 a1,a2,...,ana1, a2, ..., an .

Little Tommy is among them. He would like to choose an interval [l,r] (1lrn)[l, r] (1 ≤ l ≤ r ≤ n), then reverse al,al+1,...,aral, al + 1, ..., ar 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 p1,p2,...,pkp1, p2, ..., pk , such that p1<p2<...<pkp1 < p2 < ... < pk and ap1ap2...apkap1 ≤ ap2 ≤ ... ≤ apk . The length of the subsequence is kk .

 

Input

The first line contains an integer n (1n2000) , denoting the length of the original sequence.

The second line contains nn space-separated integers, describing the original sequence a1,a2,...,an (1ai2,i=1,2,...,n) .

 

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

 

题意

在一个只包含 1,21,2 的序列中,翻转其中任意一个区间,求此时最大的 LIS 。

 

思路

正着倒着预处理出每一段的 LIS,分别记为 L[i][j],R[i][j]L[i][j],R[i][j]

然后开始枚举,翻转一个区间相当于减去这段区间的贡献,然后加上其翻转以后的

此时 LIS 为 L[0][n1]L[i][j]+R[i][j]L[0][n−1]−L[i][j]+R[i][j]

 

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值