动态规划-基础篇——最长上升子序列(nlogn)

我写这片博文就只是提醒自己不要理解而已,其中只是一个结论,其实的证明,思路啥的都没写,以后搞dp专题的时候会全部补上,这里只是一个开头。



对于最长上升子序列(LIS)问题中,一直对lower_bound(),和upper_bound()分不清楚。

用法是:如果是严格LIS,则用的是lower_bound(),

如果是非严格LIS,则用的是upper_bound();


例如对于序列{3,4,4,5,4,4,4,4,4,4,6};

则严格Lis为{3,4,5,6},长度为4

而非严格LIS为{3,4,4,4,4,4,4,6}长度为8

代码如下
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <queue>
#include <stack>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn=30000+5;
int b[maxn],a[maxn];
int LISdp(int n)
{
    int i,k;
    b[1]=a[1];
    for(i=2,k=1;i<=n;i++)
    {
        if(a[i]>=b[k])  b[++k]=a[i];
        else
        {
            int pos=upper_bound(b+1,b+1+k,a[i])-b;//非严格
            b[pos]=a[i];
        }
    }
    return k;
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out2.txt","w",stdout);
    int n;
    while(cin>>n){
        for(int i=1;i<=n;i++){
            cin>>a[i];
        }
        int ans=LISdp(n);
        cout<<n-ans<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值