2014.7.14 CodeForces C题 字符串上的动态规划

本文探讨了在序列中寻找最长严格单调递增子序列的问题,通过枚举断点的方法来优化解决方案,提供了代码实现及解析。

题目大意是给你一个序列,让你最多改动一个点,求它的最长严格上升子序列。

开始想用尺取法做,结果发现太复杂了,if else写不清楚。。。

方法:枚举断点,前面一定是严格单调递增的,后面也是

/*ChasingWaves 	446A - DZY Loves Sequences 	GNU C++ 	Accepted 	31 ms 	1200 KB */
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

const int maxn = 100000;
int a[maxn+5];
int l[maxn+5], r[maxn+5]; //l[i]表示以a[i]结尾的最长严格单增序列长度,r[i]表示以a[i]开头的最长严格单增序列长度

inline int max(int a, int b){
    return a > b ? a : b;
}

int main(){
    int n;
    while(scanf("%d", &n) != EOF){
        for(int i=0; i<n; i++)
            scanf("%d", &a[i]);
        if(n == 1){
            printf("1\n");
            continue;
        }
        else if(n == 2){
            printf("2\n");
            continue;
        }
        memset(l, 0, sizeof(l));
        memset(r, 0, sizeof(r));
        l[0] = 1;
        for(int i=1; i<n; i++){
            if(a[i] > a[i-1]) l[i] = l[i-1] + 1;
            else l[i] = 1;
        }
        r[n-1] = 1;
        for(int i=n-2; i>=0; i--){
            if(a[i] < a[i+1]) r[i] = r[i+1] + 1;
            else r[i] = 1;
        }
        int res = max(1+r[1], l[n-2]+1); //只有左半区间或只有右半区间
        for(int i=1; i<n-1; i++){
            if(a[i+1] >= a[i-1]+2) res = max(res, l[i-1]+1+r[i+1]); //两个区间可以连接
            else res = max(res, max(l[i-1]+1, 1+r[i+1]));
        }
        printf("%d\n", res);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值