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;}