最长递增子序列

http://acm.tzc.edu.cn/acmhome/problemdetail.do;jsessionid=558B14243DB112F263306E7D3741A8A9?&method=showdetail&id=1052

在《编程之美》看过这题,中间利用二分查找可以把复杂度从O(N^2)降低到O(NlogN)

 

#include <stdio.h>
#define N 10001
 

int LIS(int * arr , int n)
{
int BIS[N+1] , nMaxLen;
int i , l , r , m , u;

//Init
BIS[1] = arr[0]; nMaxLen = 1;

for(i = 1 ; i < n ; i++)
{
//BiSearch BIS[]
l = 1; r = nMaxLen;
while(l + 1 < r)
{
m
= (l + r) / 2;
if(BIS[m] < arr[i])
l
= m;
else
r
= m;
}
if(BIS[r] < arr[i])
u
= r;
else if(BIS[l] < arr[i])
u
= l;
else
u
= 0;

//update BIS[]
if(u == nMaxLen)
{
nMaxLen
++;
BIS[nMaxLen]
= arr[i];
}
else
{
if(BIS[u+1] > arr[i])
BIS[u
+1] = arr[i];
}
}
return nMaxLen;
}

int main(void)
{
int arr[N] , n ,i;

while(scanf("%d", &n) != EOF )
{
for(i = 0 ;i < n ; i++)
scanf(
"%d", arr + i);

printf(
"%d\n",LIS(arr,n));
}

return 0;
}

 

posted on 2010-04-16 20:05  DiaoCow  阅读(308)  评论(0编辑  收藏  举报

导航