LIS 的 n*logn 写法并标记输出其中任意一个

<pre name="code" class="cpp">#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 3010;
int q[maxn],path[maxn],c[maxn],st[maxn],n;
//q:最长上升子序列的下标,path:该位置在上升子序列中前一个位置的下表 c:原序列,st:最后保存一个最长上升子序列

int bin_search(int x,int l,int r)//返回已知的最长上升子序列中最后一个小于x的位置+1
{
    while(l<=r)
    {
        int mid=(l+r)>>1;
        if(c[q[mid]]<x)
            l=mid+1;
        else
            r=mid-1;
    }
    return l;
}

int main()
{
    //freopen("lis.in","r",stdin);
    //freopen("lis.out","w",stdout);
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; i++)
            scanf("%d",&c[i]);
        int len=0;
        q[len++]=0;
        path[0]=0;
        for(int i=0; i<n; i++)
        {
            if(c[i]>c[q[len-1]])//已求的序列中没有比这个数大的,最长上升子序列加1
            {
                path[i]=q[len-1];
                q[len++]=i;
            }
            else
            {
                int idex = bin_search(c[i],0,len-1);//寻找已知子序列中最后一个比它小的位置,该数放在其后
                path[i] = idex ? q[idex-1] : 0;
                q[idex] = i;
            }
        }
        int k=0;
        printf("%d\n",len);
        st[k++]=c[q[len-1]];
        int tmp=q[len-1];
        while(--len)
        {
            tmp = path[tmp];
            st[k++]=c[tmp];
        }
        for(int i=k-1;i>=0;i--)
            printf(i==0?"%d\n":"%d ",st[i]);
    }
    return 0;
}
/**

7
2 3 1 4 0 3 6

*/




                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值