您的位置:首页 > 产品设计 > UI/UE

Codeforces Round #FF (Div. 1) A. DZY Loves Sequences 动态规划

2016-05-25 19:49 295 查看

A. DZY Loves Sequences

题目连接:

http://www.codeforces.com/contest/446/problem/A

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 contains n integers a1, 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

6

7 2 3 1 5 6

Sample Output

5

Hint

题意

让你找到一个区间,你可以改变这个区间的一个数,然后使得这个区间是严格上升的

且这个区间一定是最长的,输出区间长度

题解:

dp1[i]表示从左边开始的最长上升子串,dp2[i]是右边开始的最长上升子串

然后我们枚举i,那么答案就显然是在a[i-1]<a[i+1]-1的情况下,ans=max(ans,dp1[i-1]+dp2[i+1]+1)这个玩意儿

然后不停转移就好了

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+7;
int dp1[maxn],dp2[maxn],a[maxn];
int main()
{
int n;
scanf("%d",&n);a[0]=1e9+7,a[n+1]=1e9+7;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
if(n==1)return puts("1"),0;
if(n==2)return puts("2"),0;
int ans=0;
for(int i=1;i<=n;i++)
{
dp1[i]=1;
if(a[i]>a[i-1])dp1[i]=dp1[i-1]+1;
ans=max(ans,dp1[i]);
}
for(int i=n;i>=1;i--)
{
dp2[i]=1;
if(a[i]<a[i+1])dp2[i]=dp2[i+1]+1;
ans=max(ans,dp2[i]);
}
for(int i=1;i<=n;i++)
{
if(a[i-1]<a[i+1]-1)
ans=max(ans,dp1[i-1]+dp2[i+1]+1);
}
for(int i=2;i<=n;i++)ans=max(ans,dp2[i]+1);
for(int i=1;i<n;i++)ans=max(ans,dp1[i]+1);
cout<<ans<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: