codeforces 447C DZY Loves Sequences(最长上升子序列变体)

Description

DZY has a sequence a, consisting of n integers.

We'll call a sequence ai, ai + 1, ..., aj(1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value(j - i + 1) denotes the length of the subsegment.

Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.

You only need to output the length of the subsegment you find.

Input

The first line contains integer n (1 ≤ n ≤ 105). The next line containsn integersa1, a2, ..., an (1 ≤ ai ≤ 109).

Output

In a single line print the answer to the problem — the maximum length of the required subsegment.

Sample Input

Input
6
7 2 3 1 5 6
Output
5


解题思路:最初的想法就是直接计算一下,忽视了算法复杂度的问题。WA了几次后又TLE.....正确的做法应该是动态规划,先分别求出从前往后和从后往前的最长递增子序列的长度,然后再考虑通过更换元素能否将两者连在一起,其中很重要的一点就是更换元素两侧的差要大于等于2~

TLE代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[100005];
int n;
int find(int i)
{
    int j;
    int flag = 0;
    for(j=i;j<n-1;j++)
    {
        if(a[j]<a[j+1])
            continue;
        else
        {
                if(flag==1)
                    break;
                else
                {
                    flag = 1;
                    if(j+1 == n-1)
                        return j-i+2;
                    else if(a[j+2]-a[j]<2)
                        return j-i+2;
                }
        }

    }
    return j-i+1;
}
int main()
{
    freopen("test.txt","r",stdin);
    scanf("%d",&n);
    int i;
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    int ans = 0;
    for(i=0;i<n-1;i++)
    {
        int num = find(i);
        ans = max(ans,num);
    }
    cout << ans << endl;
    return 0;
}

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[100005];
int n;
int dp1[100005];
int dp2[100005];
int main()
{
    //freopen("test.txt","r",stdin);
    scanf("%d",&n);
    int i;
    for(i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    int ans = 0;
    dp1[0] = 0;
    dp1[1] = 1;
    dp2[n] = 1;
    dp2[n+1] = 0;
    for(i=2;i<=n;i++)//从前向后的最长上升子序列
    {
        if(a[i]>a[i-1])
            dp1[i] = dp1[i-1] + 1;
        else
            dp1[i] = 1;
    }
    for(i=n-1;i>=1;i--)//从后往前的最长下降子序列
    {
        if(a[i+1]>a[i])
            dp2[i] =dp2[i+1] + 1;
        else
            dp2[i] = 1;
    }
    /*for(i=1;i<=n;i++)
    {
        ans = max(ans,dp1[i]);
    }*/
    for(i=1;i<=n;i++)//对两种情况进行拼接组合
    {
        a[i+1] - a[i-1]>=2 ? ans = max(ans,dp1[i-1] + dp2[i+1] + 1) : ans = max(ans,max(dp1[i-1],dp2[i+1])+1);
    }
    cout << ans << endl;
    return 0;
}



你可能感兴趣的:(ACM,codeforces)