int LISOn2(int a[],int tot) { for(int i=1; i<=tot; i++) { dp[i]=1; head[i]=-1; } for(int i=1; i<=tot; i++) { int m=0,h=-1; for(int j=1; j<i; j++) { if(a[i]>a[j]&&dp[j]>m) { m=dp[j]; h=j; } dp[i]=m+1; head[i]=h; } } int ans=0,pos=0; for(int i=1; i<=tot; i++) { if(dp[i]>ans) { ans=dp[i]; pos=i; } } int top=0; for(int i=pos; i!=-1; i=head[i]) { lis[top++]=a[i]; //cout<<lis[top-1]<<" "; } return ans; }
int LISOnlogn(int a[],int tot) { int len=1; dp[1]=a[1]; for(int i=2; i<=tot; i++) { if(a[i]>dp[len]) dp[++len]=a[i]; else { int r=len,l=1; while(r>=l) { int mid=(r+l)/2; if(a[i]>=dp[mid]) l=mid+1; else r=mid-1; } dp[l]=a[i]; } } return len; }
#include <iostream> #include <cstdio> #define maxn 1005 using namespace std; int a[maxn],dp[maxn],head[maxn],lis[maxn]; int LISOnlogn(int a[],int tot) { int len=1; dp[1]=a[1]; for(int i=2; i<=tot; i++) { if(a[i]>dp[len]) dp[++len]=a[i]; else { int r=len,l=1; while(r>=l) { int mid=(r+l)/2; if(a[i]>=dp[mid]) l=mid+1; else r=mid-1; } dp[l]=a[i]; } } return len; } int LISOn2(int a[],int tot) { for(int i=1; i<=tot; i++) { dp[i]=1; head[i]=-1; } for(int i=1; i<=tot; i++) { int m=0,h=-1; for(int j=1; j<i; j++) { if(a[i]>a[j]&&dp[j]>m) { m=dp[j]; h=j; } dp[i]=m+1; head[i]=h; } } int ans=0,pos=0; for(int i=1; i<=tot; i++) { if(dp[i]>ans) { ans=dp[i]; pos=i; } } int top=0; for(int i=pos; i!=-1; i=head[i]) { lis[top++]=a[i]; } return ans; } int main() { int tot; scanf("%d",&tot); for(int i=1; i<=tot; i++) scanf("%d",&a[i]); int ans=LISOn2(a,tot); //ans=LISOnlogn(a,tot); cout<<ans<<endl; return 0; }
POJ 2533 Longest Ordered Subsequence 最长上升子序列
原文地址:http://blog.csdn.net/ooooooooe/article/details/24623721