题目:click here
题意:求给定序列更改其中一个元素后的最长连续上升子序列的长度
分析:最长的连续子序列有2种,一种是严格上升(没有更改元素)的长度加1,一种是两段严格上升的加起来。、
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define F first 4 #define S second 5 #define pb push_back 6 #define power(a) ((a)*(a)) 7 #define ENTER printf("\n"); 8 typedef unsigned long long ll; 9 const int INF = 0x3f3f3f3f; 10 const double EPS = 1e-8; 11 const int M = 1e5+5; 12 13 int n; 14 int a[M]; 15 int dps[M]; // dps[i]保存以i开头的最长连续上升子序列 16 int dpe[M]; // dpe[i]保存以i结束的最长连续上升子序列 17 void solve() { 18 dpe[0] = 1; 19 dps[n-1] = 1; 20 int ret = 1; 21 for( int i=1; i<n; i++ ) { 22 if( a[i] > a[i-1] ) dpe[i] = dpe[i-1] + 1; 23 else dpe[i] = 1; 24 ret = max( ret, dps[i] ); 25 } 26 for( int i=n-2; i>=0; i-- ) { 27 if( a[i] < a[i+1] ) dps[i] = dps[i+1] + 1; 28 else dps[i] = 1; 29 ret = max( ret, dps[i] ); 30 } 31 for( int i=0; i<n; i++ ) { 32 if( i == 0 ) 33 ret = max( ret, dps[i]+1 ); 34 else if( i == n-1 ) 35 ret = max( ret, dpe[i]+1 ); 36 else { 37 if( a[i+1]-a[i-1] >= 2 ) 38 ret = max( ret, dps[i+1]+dpe[i-1]+1 ); 39 else 40 ret = max( ret, max( dps[i+1]+1, dpe[i-1]+1 ) ); 41 } 42 } 43 printf("%d\n", ret>n?n:ret ); // 结果最大为n 44 } 45 int main() { 46 while( ~scanf("%d", &n ) ) { 47 for( int i=0; i<n; i++ ) 48 scanf("%d", a+i); 49 solve(); 50 } 51 return 0; 52 }
时间: 2024-11-08 08:50:17