题意:求LIS
思路:nlogn写发,动态维护一个数组ci,ci记录上升序列长度为i的最末位数字的最小值,c0初始化为-inf,c1=a1,ci=inf(i>1),对于每一个ai(i>1)来说,总能在ci中找到比他小的数,每次在c中找到最后一个比ai大的数k,则dp[i]=k+1,并且更新c[k+1]的值,c[k+1]=min(c[k+1],ai),由于ai>c[k],所以ci始终保持是一个单调递增的状态,因此可以二分找到最大的k,把复杂度降低到nlogn
AC代码:
#include "iostream" #include "string.h" #include "stack" #include "queue" #include "string" #include "vector" #include "set" #include "map" #include "algorithm" #include "stdio.h" #include "math.h" #define ll long long #define bug(x) cout<<x<<" "<<"UUUUU"<<endl; #define mem(a) memset(a,0,sizeof(a)) #define mp(x,y) make_pair(x,y) using namespace std; const long long INF = 1e18+1LL; const int inf = 1e9+1e8; const int N=1e5+100; const ll mod=1e9+7; int n,mr,arr[N],c[N],dp[N]; int main(){ ios::sync_with_stdio(false),cin.tie(0),cout.tie(0); int T; cin>>T; while(T--){ cin>>n; mem(dp); for(int i=1; i<=n; ++i){ cin>>arr[i]; c[i]=inf; } int cnt=0; c[0]=-inf,c[1]=arr[1]; for(int i=2; i<=n; ++i){ int l=0,r=n,ans=0; int p=arr[i]; while(l<=r){ int mid=l+r>>1; if(c[mid]<p){ ans=mid; l=mid+1; } else r=mid-1; } dp[i]=ans+1; cnt=max(cnt,dp[i]); c[ans+1]=min(c[ans+1],arr[i]); } cout<<cnt<<endl; } return 0; }