nyist oj 17 单调递增最长子序列 (动态规划经典题)

来源:互联网 发布:java中i和 i的区别 编辑:程序博客网 时间:2024/06/03 05:27

单调递增最长子序列

时间限制:3000 ms  |  内存限制:65535 KB
难度:4
描述
求一个字符串的最长递增子序列的长度
如:dabdbf最长递增子序列就是abdf,长度为4
输入
第一行一个整数0<n<20,表示有n个字符串要处理
随后的n行,每行有一个字符串,该字符串的长度不会超过10000
输出
输出字符串的最长递增子序列的长度
样例输入
3aaaababcabklmncdefg
样例输出
137
来源

经典题目

动态规划的经典题目;好像还有好几种解法,我现在研究的是最基础的解法;


这里直接参考了 http://blog.csdn.net/sjf0115/article/details/8715672  的博客,把其中的图片复制过来了,感觉讲的还不错,加深对这类题目的理解;

http://www.cnblogs.com/mycapple/archive/2012/08/22/2651453.html  这篇博客讲的也不错

[cpp] view plain copy
  1. #include <cstdio>  
  2. #include <cstring>  
  3. const int maxn=10001;  
  4. char s[maxn];  
  5. int dp[maxn],Max;  
  6. void LICS()  
  7. {  
  8.     int len;  
  9.     memset(dp,0,sizeof(dp));  
  10.     len=strlen(s);  
  11.     for(int i=0;i<len;i++)  
  12.     {  
  13.         dp[i]=1;//给定一个数组求的时候,初始值就是1,一个数组的最大序列肯定会有一个字符;  
  14.         for(int j=0;j<i;j++)  
  15.         {  
  16.             if(s[i]>s[j] && dp[i]<1+dp[j])// 递推公式,如果这个位置比前面的字符都大,就加入到递增序列中来  
  17.                 dp[i]=1+dp[j];  
  18.         }  
  19.     }  
  20.     Max=0;  
  21.     for(int i=0;i<len;i++)//求出最大值  
  22.         if(Max<dp[i])  
  23.           Max=dp[i];  
  24. }  
  25. int main()  
  26. {  
  27.     int t;  
  28.     scanf("%d",&t);  
  29.     while(t--)  
  30.     {  
  31.         scanf("%s",s);  
  32.         LICS();  
  33.         printf("%d\n",Max);  
  34.     }  
  35.     return 0;  
  36. }  

看到了这道题的最优代码;上面我写的提交300多ms,最优代码只要4ms,0ms也许也可以达到;

但是有点看不懂的节奏啊,保存学习一下;

[cpp] view plain copy
  1.    
  2.    
  3. #include<iostream>  
  4. #include <string>  
  5. //#include <time.h>  
  6. using namespace std;  
  7. int main()  
  8. {  
  9.     //freopen("1.txt","r",stdin);  
  10.     int n ;  
  11.     cin>>n;  
  12.     while(n--)  
  13.     {  
  14.         string str;  
  15.         int count=1;  
  16.         cin>>str;  
  17.         int a[200];  
  18.         a[0]=-999;  
  19.         for (int i=0;i<str.length();i++)  
  20.         {  
  21.   
  22.             for (int j=count-1;j>=0;j--)  
  23.             {  
  24.                 if((int)str[i]>a[j])  
  25.                 {  
  26.                     a[j+1]=str[i];  
  27.                     if(j+1==count) count++;  
  28.                     break;  
  29.                 }  
  30.             }  
  31.         }  
  32.         cout<<count-1<<endl;  
  33.     }  
  34.     //cout<<(double)clock()/CLOCKS_PER_SEC<<endl;  
  35.     return 0;  
  36. }                  

原文地址:http://blog.csdn.net/whjkm/article/details/38582411

阅读全文
0 0