本文主要是介绍Codeforces Round #FF (Div. 2/C)/Codeforces446A_DZY Loves Sequences(DP),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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.
The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).
In a single line print the answer to the problem — the maximum length of the required subsegment.
6 7 2 3 1 5 6
5
You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.
解题报告
改变任意一个位置的数(最大只能改变一个),求最大上升子序列长度。
DP1[i]表示以i为终点的最大子序列长度,DP2[i]表示以i为起点的最大子序列长度。
在区间2到n-1里面,如果存在一个区间类似1,4,6,3,8,9/可以改变3(i)的值为7,那么最大上升子序列应该是dp1[i-1]+dp2[i+1]+1。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;int n,num[100010],dp1[100010],dp2[100010];
int main()
{int i,j;while(~scanf("%d",&n)){int maxx=1;for(i=0; i<n; i++)scanf("%d",&num[i]);dp1[0]=1;for(i=1; i<n; i++){if(num[i-1]<num[i])maxx++;else{dp1[i]=1;maxx=1;}dp1[i]=maxx;}maxx=1;dp2[n-1]=1;for(i=n-2; i>=0; i--){if(num[i+1]>num[i])maxx++;else{dp2[i]=1;maxx=1;}dp2[i]=maxx;}int ans=1;
// for(i=0;i<n;i++)
// {
// cout<<dp1[i]<<" ";
// }
// cout<<endl;
// for(i=0;i<n;i++)
// cout<<dp2[i]<<" ";
// cout<<endl;for(i=0; i<n; i++){if(i==n-1)ans=max(ans,dp1[i-1]+1);else if(i==0)ans=max(ans,dp2[i+1]+1);else if(num[i+1]-num[i-1]>1){ans=max(ans,dp1[i-1]+dp2[i+1]+1);}else ans=max(ans,max(dp1[i-1]+1,dp2[i+1]+1));}cout<<ans<<endl;}return 0;
}
这篇关于Codeforces Round #FF (Div. 2/C)/Codeforces446A_DZY Loves Sequences(DP)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!