您的位置:首页 > 编程语言 > PHP开发

最长不下降子序列(动态规划)

2011-12-14 16:04 351 查看
一个数的序列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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  output input bi