int bisert(int c[1000000],int j,int ai)
{
int low=1;
int high=j;
int mid;
while(low<=high)
{
mid=(high+low)/2;
if(c[mid]<ai){
if(c[mid+1]>ai)
return mid;
else
low=mid+1;
}
else{
if(c[mid-1]<ai)
return mid-1;
else
high=mid-1;
}
}
return low;
}
#include<stdio.h>
int a[1000000];
int c[1000000];
int main(){
int length;
scanf("%d",&length);
int i;
for(i=0;i<length;i++)
scanf("%d",&a[i]);
c[1]=a[0];//c[i] stands for the smallest ending number of all increasing sequences with length i
int j=1;//j is the length of the longest increasing sequence currently
int k;
for(i=1;i<length;i++){
if(c[1]>a[i]){//set a[i] as the smallest ending number of all increasing sequences with length 1
c[1]=a[i];
}
else if(c[j]<a[i]){//a[i] can be put into the extended increasing sequence of lenght j+1
j++;
c[j]=a[i];
}
else{//a[i] can be put into the extended increasing sequence of lenght k+1 for some k, such that 1<k<j
k=bisert(c,j,a[i]);
c[k+1]=a[i];
}
}
printf("%d\n",j);
return 0;
}
问题详见poj2533。
如果这里数组的长度要求100,0000,那么O(n^2)的算法就不能用了。上面的算法只用了O(nlogn)时间。