1. 程式人生 > >最長遞增子序列(只求大小)模板

最長遞增子序列(只求大小)模板

初始化 輸入 div 分法 下界 ive tdi color ostream

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 40005
int main(){
    int a[8] = {5,4,6,8,7,10,3,6};
    int f[10];
    f[0] = 1;
    int ans = 0;
    for(int i=1;i<8;i++){
        f[i] = 1;
        for(int j=0;j<i;j++){//
當j小於i(序列號),且j本身的數值也小於i本身的數值則滿足排列的條件 if(a[j]<a[i]&&f[j]>f[i]-1){//之所以是大於f[i]-1是因為要保證現在的遞增子序列是最長的 f[i] = f[j] + 1;//加一加的是本身這個數 } } ans = max(ans,f[i]);//ans求的是最長的長度,最後一個不一定是最長的 } cout << ans << endl; return 0; }


用二分法加快了查找符合條件的數構成遞增子序列的過程

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
int main(){
    int a[8] = {5,4,6,8,7,10,3,6};
    int B[9]; 
    B[0]=-10000;//把B[0]設為最小,假設任何輸入都大於-10000;
    B[1]=a[0];//初始時,最大遞增子序列長度為1的最末元素為a1
    int Len = 1;//Len為當前最大遞增子序列長度,初始化為1;
int p,r,m;//p,r,m分別為二分查找的上界,下界和中點; for(int i = 1;i<8;i++) { p=0;r=Len; while(p<=r)//二分查找最末元素小於ai+1的長度最大的最大遞增子序列; { m = (p+r)/2; if(B[m]<a[i]) p = m+1; else r = m-1; } B[p] = a[i];//將長度為p的最大遞增子序列的當前最末元素置為ai+1; if(p>Len) Len++;//更新當前最大遞增子序列長度; } cout << Len << endl; return 0; }

參考博客

http://www.cnblogs.com/lonelycatcher/archive/2011/07/28/2119123.html

註 這個博客求最長時錯了

最長遞增子序列(只求大小)模板