最長不下降子序列(動態規劃)

一個數的序列bi,當b1 <= b2 <= ... < =bS的時候,我們稱這個序列是不下降的。對於給定的一個序列(a1, a2, ..., aN),我們可以得到一些不下降的子序列(ai1, ai2, ..., aiK),這裏1<= i1 < i2 < ... < iK <= N。比如,對於序列(1, 7, 3, 5, 9, 4, 8),有它的一些不下降子序列,如(1, 7), (3, 4, 8)等等。這些子序列中最長的長度是4,比如子序列(1, 3, 5, 8)。

Input

 

多組cas , 每組cas 兩行:

第一行 輸入一個數 n (n < 10000), 表示有n個數

第二行 n個數, 分別代表每個數;

Output

每個cas 一行  輸出 該書數列的最長的長度 ;

Sample Input

7

1 7 3 5 9 4 8

Sample Output

4


思路:從後面開始遍歷


#include<iostream>
#define MAX 10001
void vInput(int nArray[],int nN);
int nGetResult(int nArray[],int nN);
void vOutput(int nResult);
int main(){
 int nN;
 int nArray[MAX];
 int nResult;
 while(1==scanf("%d",&nN)){
  vInput(nArray,nN);
  nResult=nGetResult(nArray,nN);
  vOutput(nResult);
 }
 return 0;
}
void vInput(int nArray[],int nN){
 int i;
 for(i=1;i<=nN;i++){
  scanf("%d",&nArray[i]);
 }
}
int nGetResult(int nArray[],int nN){
 int nF[MAX];
 int nResult=1;
 int nTemp;
 int i;
 int j;
 for(i=1;i<=nN;i++){
  nF[i]=1;
 }
 for(i=nN-1;i>=1;i--){
  nTemp=1;
  for(j=i+1;j<=nN;j++){
   if((nArray[i]<=nArray[j])&&nTemp<nF[j]+1){
    nTemp=nF[j]+1;
   }
  }
  nF[i]=nTemp;
  if(nResult<nF[i]){
   nResult=nF[i];
  }
 }
 return nResult;
}
void vOutput(int nResult){
 printf("%d\n",nResult);
}

發佈了44 篇原創文章 · 獲贊 12 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章