標籤:codeforces c. dzy loves sequences lis升級
題目:C. DZY Loves Sequences (LIS升級)
題意:
在n個數中,最多改變一個數字,並求能夠達到的最長嚴格上升子序列(連續)長度
分析:
考慮第i個數,能否改變後拼接前後兩個字串,並維護當前最大值
狀態:
left[i]: 表示以i為終點的最長嚴格上升子序列長度
right[i]: 表示以i為起點的最長嚴格上升子序列長度
dp[i]: 表示改變第i個數後,拼接前後字串的長度
轉移方程:
dp[i] = max{left[i-1] + right[i+1] + 1 | a[i-1] + 1 < a[i+1]};
核心:
for(i = 1; i<=n; i++){ if(a[i-1] >= a[i]) ans = max(ans, right[i] + 1); if(a[i+1] <= a[i]) ans = max(ans, left[i] + 1); if(a[i-1] + 1 < a[i+1]) ans = max(ans, left[i-1] + right[i+1] + 1);}
代碼:
#include <stdio.h>#include <iostream>#include <math.h>#include <algorithm>#include <string.h>#include <string>#include <queue>#include <stack>#include <map>#include <vector>#include <time.h>using namespace std;int a[100000+10];int L[100000+10];int R[100000+10];int main(){//freopen("a.txt", "r", stdin);int n, i, j;while(~scanf("%d", &n)){for(i = 1; i<=n; i++){scanf("%d", &a[i]);}memset(L, 0, sizeof(L));for(i = 1; i<=n; i++){L[i] = 1;if(i>1 && a[i] > a[i-1]){L[i] = max(L[i], L[i-1]+1);}}memset(R, 0, sizeof(R));int ans = 0;for(i = n; i>=1; i--){R[i] = 1;if(i<n && a[i] < a[i+1]){R[i] = max(R[i], R[i+1]+1);}ans = max(ans, R[i]);}for(i = 1; i<=n; i++){if(i>1 && a[i-1] >= a[i])ans = max(ans, L[i-1] + 1);if(i<n && a[i] >= a[i+1])ans = max(ans, R[i+1] + 1);if(i>1 && i<n && a[i-1] + 1 < a[i+1])ans = max(ans, L[i-1] + R[i+1] + 1);}printf("%d\n", ans);}return 0;}