nlogn 最長不下降子序列

來源:互聯網
上載者:User

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

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.