题目链接: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();
}