最長單調遞增子序列

 

下標

1

2

3

4

5

6

7

8

數組a

65

158

170

155

239

300

207

389

數組b

1

2

3

2

4

5

4

6

 完整程序:

#include<bits/stdc++.h>
using namespace std;
// 計算最長遞增子序列的動態規劃算法
#define NUM 100
int a[NUM];//序列L
int LIS_n2(int n)//教材上這一句丟掉了
{
int b[NUM]={0};//輔助數組b
int i,j;
b[1] = 1;
int max = 0;//數組b的最大值
for(i=2;i<=n; i++)
{
int k = 0;
for(j=1; j<i; j++)//0~i-1之間,b的最大值
if(a[j]<=a[i] && k<b[j]) k=b[j];
b[i] = k+1;
if(max<b[i]) max=b[i];
}
return max;
}
int main(){
    int n;
    cout<<"請輸入數據個數"<<endl;
    cin>>n;
   cout<<"請輸入"<<n<<"個數據個數"<<endl;
   for(int i=1;i<=n;i++){
    cin>>a[i];
   }
   cout<<"最長單調遞增子序列的長度爲"<<endl;
   cout<<LIS_n2(n);
return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章