用空间换时间,将求解最大非递增子序列问题的时间复杂度降为O(N logN)
#include <stdio.h>
#include <stdlib.h>
int BinarySearch(int leftBound,int rightBound,int A[],int loopIndex,int minor[])
{
int midIndex;
while (leftBound<=rightBound)
{
midIndex = (leftBound+rightBound)/2;
if (minor[midIndex]<A[loopIndex])
{
leftBound = midIndex+1;
}
else
{
rightBound = midIndex-1;
}
}
return leftBound;
}
int MaxSubLength(int A[],int ALength)
{
//辅助矩阵
int *minor = (int *)malloc(ALength*sizeof(int));
int LoopIndex,leftBound,rightBound,MaxLength=1,insertPosition;
minor[0] = A[0];
for (LoopIndex=1;LoopIndex<ALength;LoopIndex++)
{
leftBound=0;
rightBound=MaxLength;
insertPosition = BinarySearch(leftBound,rightBound,A,LoopIndex,minor);
minor[insertPosition]=A[LoopIndex];
if (insertPosition>MaxLength)
{
MaxLength++;
}
}
free(minor);
return MaxLength;
}
int main()
{
int A[11] = {2,1,5,3,6,4,8,9,7,8,9};
int maxLength;
maxLength = MaxSubLength(A,11);
printf("the length is %d",maxLength);
getchar();
return 0;
}