• POJ 2533 最小上升子序列


    D - POJ 2533 经典DP-最长上升子序列

     A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence ( a1a2, ..., aN) be any sequence ( ai1ai2, ..., aiK), where 1 <= i1 < i2 < ... < iK <= N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g., (1, 7), (3, 4, 8) and many others. All longest ordered subsequences are of length 4, e. g., (1, 3, 5, 8). 

    Your program, when given the numeric sequence, must find the length of its longest ordered subsequence.

    Input

    The first line of input file contains the length of sequence N. The second line contains the elements of sequence - N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000

    Output

    Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence.

    Sample Input

    1 7 3 5 9 4 8

    Sample Outout

    4

    经典的DP,但是作为新手一开始想岔了,想着状态方程best(i)是表示前 i 个数字的最长子序列长度,然后用一个数组记录前 i 个数字的最长自序列的最后一项,则best(i)就等于将第i个数和组成前i - 1 个最长序列的最后一个一项进行比较, 若大于最后一项,则长度+1, 否则保持原长度。最后从i = N,一步步递归到i = 1。

    但很明显这种想法错了,因为并不能满足最优子结构,一开始觉得自己一下就找到方法了就没细想....

    正确答案是,best(i)表示以第i个数结尾的最长子序列,这样就需要两层循环,外层i = 1 ------>i = N, 内层 j = 1 ------>j = i - 1

     AC代码如下

     1 #include <iostream>
     2 #include <stdio.h>
     3 #include <string.h>
     4 #include <algorithm>
     5 #pragma warning ( disable : 4996 )
     6 
     7 using namespace std;
     8 
     9 int N, map[1015], best[1015];
    10 int max;
    11 
    12 
    13 int main()
    14 {
    15 
    16     while ( ~scanf( "%d", &N ) ) 
    17     {
    18         memset( map, 0, sizeof(map) );
    19         memset( best, 0, sizeof(best) );
    20         //memset( dp, 0, sizeof(map) );
    21 
    22 ///////////////////////////////////////////////////////
    23         for( int i = 1; i <= N; i++ )
    24             scanf( "%d", &map[i] );
    25 ///////////////////////////////////////////////////////
    26         for ( int i = 1; i <= N; i++ )
    27         {
    28             int max = 0;
    29             for ( int j = 1; j < i; j++ )
    30                 if( map[i] > map[j] && max < best[j] )
    31                     max = best[j];
    32             best[i] = max + 1;
    33         }
    34         int max = 0; 
    35         for( int i = 1; i <= N; i++ )
    36             if( max < best[i] )
    37                 max = best[i];
    38         cout << max << endl;
    39     }
    40     return 0;
    41 }



  • 相关阅读:
    与答辩有关资料
    SpringBoot技术优点
    【知识库】-简单理解CrudRepository接口中的方法
    【知识库】-通俗理解OAuth2.0协议用于第三方登陆
    毕业设计介绍所用
    JavaWeb_(视频网站)_七、推荐模块1
    JavaWeb_(视频网站)_六、分页模块1
    JavaWeb_(视频网站)_五、视频模块2 辅助功能
    JavaWeb_(视频网站)_五、视频模块1 视频上传
    JavaWeb_(视频网站)_四、博客模块2
  • 原文地址:https://www.cnblogs.com/chaoswr/p/7846284.html
Copyright © 2020-2023  润新知