线性dp—acwing

题目一:最长上升子序列

895. 最长上升子序列 - AcWing题库

代码1(双指针算法,dp递推)(n^2)

#include<bits/stdc++.h>
using namespace std;

int solve(vector<int> &arr) {
    // 状态dp,dp[i] 表示此位置为止最长升序子序列长度
    int n = arr.size();
    vector<int> dp(n,1);
    //dp[0] 必然是1
    // 借助递推,从前往后加1,从比较操作中进行判断,> 说明可以在原基础dp存储长度+1;
    // 双指针比较,选取max
    for(int i = 1; i < n; i ++) {
        for(int j = 0; j < i; j ++) {
            if(arr[j] < arr[i]) 
                dp[i] = max(dp[i],dp[j]+1);
        }
    }
    //状态数组中的最大值
    return *max_element(dp.begin(),dp.end());
}

int main() {
    int n;
    cin >> n;
    vector<int> arr;
    for(int i = 0; i < n; i ++) {
        int x; cin >> x;
        arr.push_back(x);
    }
    
    int ans = solve(arr);
    
    cout << ans << endl;
    return 0;
}

代码2(二分优化)(nlogn) 与代码3一个意思

#include<bits/stdc++.h>
using namespace std;

int solve(vector<int> &arr) {
    int n = arr.size();
    
    vector<int> dp; // 本质上时vector 模拟单调栈维护最长升序子序列
    
    for(int i = 0; i < n; i ++) {
        int pos = lower_bound(dp.begin(),dp.end(),arr[i]) - dp.begin();
        //dp找不到大于等于的,说明此最大
        if(pos == dp.size()) dp.push_back(arr[i]);
        else dp[pos] = arr[i];
    }
    
    return dp.size();
}

int main() {
    int n;
    cin >> n;
    vector<int> arr;
    for(int i = 0; i < n; i ++) {
        int x; cin >> x;
        arr.push_back(x);
    }
    
    int ans = solve(arr);
    
    cout << ans << endl;
    return 0;
}

代码3(当n很大时)vector模拟单调栈维护最长上升序列

#include<bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;

    vector<int> arr(n);
    for(int i = 0; i < n; i ++) cin >> arr[i];
    
    vector<int> stk; // 模拟单调栈
    stk.push_back(arr[0]);
    
    for(int i = 1; i < n; i ++) {
        if(arr[i] > stk.back())
            stk.push_back(arr[i]);
        else
            *lower_bound(stk.begin(),stk.end(),arr[i]) = arr[i];
    }
    
    cout << stk.size() << endl;
    return 0;
}

解析(核心)

举个1 3 5 2 4 6 的例子,类似单调栈

这里相当于两个单调 1 3 5   以及 2 4 6,两个上坡

入栈 : 1 3 5   

2 替换 3:  1 2 5, 长度不改变,但是此2 会对后面的长度有影响,2  4 6 这个坡度,当然不一定是这样子的两个单调,中间隔断续那种也可以,反正就是维护单调的那个意思

4 替换 5:  1 2 4

加入5  :  1 2 4 5     最长长度为4

还可以举这样的例子

1 3 5  2 6 9  这样的在二维图中是一种 上升,断层(2) 在接着5上升那种,

2替换掉3,其余的剩余长度就是了 也就是 1 2 5 6 9, 2替换3不影响长度,虽然可能下标先后有变动,但不影响结果。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值