LIS的三种O(nlogn)解法

题目链接:LIS - 洛谷

1.最常见的做法,用栈来处理

#include <bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
#define pii pair<int,int>
#define int long long
#define ls o<<1
#define rs o<<1|1
const int N = 1e5+5;
int n, st[N], tot=0;

void solve(){
    cin>>n;
    FOR(i,1,n){
        int x; cin>>x;
        if(x>st[tot]) st[++tot]=x; //最大长度更新
        else{
            int p=lower_bound(st+1,st+tot+1,x)-st; //求最大不降子序列
            st[p]=x; //替换最优的最后数字
        }
    }
    cout<<tot;
}
signed main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int T=1; //cin>>T;
    while(T--) solve();
}

2.栈的做法的优化,更加好写,看下代码就能懂,原理和栈那个一样

#include <bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
#define pii pair<int,int>
const int N = 1e5+5, inf=0x3f3f3f3f;
int n, h[N];
void solve(){
    cin>>n;
    memset(h,0x7f,sizeof(h));
    FOR(i,1,n){
        int x; cin>>x;
        int p=lower_bound(h+1,h+n+1,x)-h;
        h[p]=x;
    }
    int p=lower_bound(h+1,h+n+1,inf)-h;
    cout<<p-1;
}
signed main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int T=1; //cin>>T;
    while(T--) solve();
}

3.权值线段树的解法

#include <bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
#define pii pair<int,int>
#define int long long
#define ls o<<1
#define rs o<<1|1
const int N = 1e5+5;
int n, t[N<<2];

void upd(int o,int l,int r,int pos,int val){
    if(l==r) {t[o]=val; return;}
    int mid = l+r>>1;
    if(pos<=mid) upd(ls,l,mid,pos,val);
    else upd(rs,mid+1,r,pos,val);
    t[o] = max(t[ls],t[rs]);
}
int query(int o,int l,int r,int x,int y){
    if(x<=l && r<=y) return t[o];
    int mid = l+r>>1, mx=0;
    if(x<=mid) mx=max(mx, query(ls,l,mid,x,y));
    if(y>mid)  mx=max(mx, query(rs,mid+1,r,x,y));
    return mx;
}
void solve(){
    cin>>n;
    FOR(i,1,n){
        int x; cin>>x;
        int mx = query(1,1,n,1,x);
        upd(1,1,n,x,mx+1);
    }
    cout<<query(1,1,n,1,n);
}
signed main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int T=1; //cin>>T;
    while(T--) solve();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值