最长XX子序列N*LOGN算法

利用二分查找。

开一个数组c,c[i] 保存长度为 i 时的最小值。

更新的时候找比a[i] 小的最长的,也就是c[k] 中k最大的,因为c是个单增的序列,所以用二分找。

看这个吧 http://felven2011.wordpress.com/2011/02/22/最长不降子序列/

zoj 1986 可以用这个练练,N比较大。以前居然用单调队列做过 T T。。忘得一干二净了。

#include <queue>
#include <stack>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <string.h>
#include <string>
#include <algorithm>

using namespace std;

const int MAX = 40005;
int a[MAX];
int f[MAX],c[MAX]; // f[i]记录以i为终点的LIS的长度 
int LIS(int *a,int n)
{
	int len = 1,k;
	f[0] = 1; c[0] = a[0];
	for(int i=1; i<n; i++)
	{
		if( a[i] <= c[0] )
			k = 1;
		if( a[i] > c[len-1] )
			k = len++;
		else
			k = upper_bound(c,c+len,a[i]) - c;
		c[k] = a[i]; f[i] = k + 1;
	}
	return len;
}
			
int main()
{
	int ncases,n;
	
	scanf("%d",&ncases);
	
	while( ncases-- )
	{
		scanf("%d",&n);
		for(int i=0; i<n; i++)
			scanf("%d",&a[i]);
		int ans = LIS(a,n);
		printf("%d\n",ans);
	}

return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值