• POJ 2533 Longest Ordered Subsequence


    Description

    A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence (a1, a2, ..., aN) be any sequence (ai1, ai2, ..., 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

    7
    1 7 3 5 9 4 8

    Sample Output

    4
    

    Source

    Northeastern Europe 2002, Far-Eastern Subregion
    分析:对于某个给定阶段状态来说,以前各阶段的状态无法直接影响到未来的决策,只能间接地通过当前状态来影响,满足无后效性,可以用动态规划来解决。
         可以得出一下结论,假设目标数组a[]的前i个元素,最长递增子序列的长度为Lis[i],那么有Lis[i+1]=max{1,Lis[k]+1},a[i+1]>a[k],对任意的k<=i。
      
      
             即如果a[i+1]大于a[k],那么第i+1个元素可接在Lis[k]长的子序列后面构成一个更长的子序列,与此同时a[i+1]本身至少也可以构成一个长度为1的子序列。
    代码如下:
    #include <stdio.h>
    
    #define MAX 1000 + 20
    
    int main()
    {
        int i,j,n,ans,a[MAX],Lis[MAX];
        while((scanf("%d",&n))!=EOF)
        {
            for(i = 0;i < n; i++)
                scanf("%d",&a[i]);
            for(i = 0; i < n; i++)
            {
                Lis[i] = 1;//初始化默认长度
                for(j = 0; j < i; j++)//前面最长的序列
                {
                    if(a[i] > a[j] && Lis[j] + 1 > Lis[i])
                        Lis[i] = Lis[j] + 1;
                }
            }
            ans = Lis[0];
            for(i = 1;i < n; i++)
                if(Lis[i] > ans)
                    ans = Lis[i];
            printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    正则校验录入日期是否有效(含润年)
    java截取字符串中字节长度【转】
    python基础总结(oop)
    python基础总结(函数)
    python基础总结(字符串)
    python基础总结(集合容器)
    python基础总结(判断语句*循环语句)
    python基础总结(基本类型与运算符)
    python爬虫相关的一些面试题
    python爬虫基本知识
  • 原文地址:https://www.cnblogs.com/zxy1992/p/3465976.html
Copyright © 2020-2023  润新知