最长上升子序列(logN算法)

例如:1 7 3 5 9 4 8
一个序列,比如说a[]={1,7,3,5,9,4,8},找出它的最长上升子序列的个数,很明显是4个,可以是{1,3,5,9},{1,3,5,8}或者{1,3,4,8}。具体怎么实现呢?直观的感受是以1为起点,下一个数比1大,那么上升子序列个数就+1,以1为起点,到7的时候,上升子序列的个数是2;到3的时候也是2,因为3>1&&3<7;再遍历下一个数5,5与1比较大于1,上升子序列的个数为2,再与7比较,5<7,子序列个数不变,再与3比较,5>3,上升子序列的个数+1,为3,以此类推,那么程序的流程大致为:
定义数组b[]用来存放a[]中每个数的上升子序列的个数,找出b[]中最大值。
 
#include
#include
using namespace std;
const int maxn=1e5+5;
const int INF=1e9+5;
int dp[maxn],v[maxn],d[maxn];
 
int main(){
    freopen("in.txt", "r", stdin);
    int n;
    while(scanf("%d",&n)!=EOF){
        v[0]=0;
        for(int i=0;i
          scanf("%d",d+i);
          v[i]=INF;
          //cout<<v<<endl;
          int f=lower_bound(v,v+i+1,d[i])-v;///lower_bound(v,v+i+1,d[i])在0到i之间查找第一个大于d[i]的下标
          dp[i]=f+1;
          v[f]=d[i];
        }
        //cout<<endl;
        int ans=-1;
        for(int i=0;i
            ans=max(ans,dp[i]);
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2016-07-30 13:25  勿忘初心0924  阅读(361)  评论(0编辑  收藏  举报