最长严格上升子序列O(nlogn)算法

来源:互联网 发布:centos ftp客户端命令 编辑:程序博客网 时间:2024/06/06 00:11

相当于二分,len表示当前最长的长度,maxl[i]表示长度为i的严格上升子序列最后一个数的最小值。满足如果i<j,则maxl[i]<maxl[j]

2017.8.29补充:注意二分的左端点是0而不是1,因为有当前数字为最小数字的情况。

//Serene//最长严格上升子序列O(nlogn)算法#include<algorithm>#include<iostream>#include<cstring>#include<cstdlib>#include<cstdio>#include<cmath>using namespace std;const int maxn=5000+10,INF=2e9;int n,dp[maxn],maxl[maxn],x,len=1;int ef(int xx,int l,int r) {if(l>=r-1) return l;int mid=(l+r)>>1;if(maxl[mid]<xx) return ef(xx,mid,r);else return ef(xx,l,mid);}int main() {scanf("%d",&n);scanf("%d",&x); maxl[1]=x;for(int i=2;i<=n;++i) {scanf("%d",&x);if(x>maxl[len]) maxl[++len]=x;else {int k=ef(x,0,len);maxl[++k]=x;}}cout<<len;return 0;}

0 0