nlogn 最长不下降子序列


O(nlogn)的算法关键是它建立了一个数组temp[],temp[i]表示长度为i的不下降序列中结尾元素的最小值,用top表示数组目前的长度,算法完成后top的值即为最长不下降子序列的长度。
设当前的以求出的长度为top,则判断num[i]和temp[top]:
1.如果num[i]>=temp[top],即num[i]大于长度为top的序列中的最后一个元素,这样就可以使序列的长度增加1,即top++,然后现在的temp[top]=num[i];
2.如果num[i]<temp[top],那么就在temp[1]...temp[top]中找到最大的j,使得temp[j]<num[i],然后因为temp[j]<num[i],所以num[i]大于长度为j的序列的最后一个元素,那么就可以更新长度为j+1的序列的最后一个元素,即temp[j+1]=num[i]。

#include<stdio.h>
int num[1000],temp[1000];
int top;
int binary_search(int x)
{
    int l=0,r=top,mid;
	while(l<=r)
	{
		mid=(l+r)>>1;
		if(temp[mid]>=x) r=mid-1;
		else //temp[mid]<x
		{
			l=mid;
			if(temp[l+1]>=x)return l+1;
			else l++;
		}
	}
}//找到序列中不大于x的最大的数,正因为二分查找才使得复杂度变身为n*log(n) 
int main()
{
	int n,i;
	while(scanf("%d",&n)==1)
	{
		for(i=0;i<n;i++)
			scanf("%d",&num[i]);
		top=0;temp[0]=num[0];
		for(i=1;i<n;i++)
		{
			if(num[i]>temp[top]) temp[++top]=num[i];
			else
			{
				if(num[i]<=temp[0]) temp[0]=num[i]; //算是
				else  temp[binary_search(num[i])]=num[i];
			}
		}
		printf("%d\n",top+1);
	}
	return 0;
}

  

posted @ 2011-11-20 22:25  Because Of You  Views(3597)  Comments(0Edit  收藏  举报