zoukankan      html  css  js  c++  java
  • Longest Ordered Subsequence

    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

    7
    1 7 3 5 9 4 8

    Sample Output

    4

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<iostream>
    using namespace std;
    #define N 10005
    int a[N], dp[N];
    
    int main()
    {
        int n, m, i, j, sum;
        while(scanf("%d", &n)!=EOF)
        {
            memset(a, 0, sizeof(a));
            memset(dp, 0, sizeof(dp));
            for(i=0;i<n;i++)
            {
                scanf("%d", &a[i]);
            }
            sum=0;
            for(i=1;i<n;i++)
            {
                for(j=0;j<i;j++)
                {
                    if(a[i]>a[j])
                    {
                        dp[i]=max(dp[j]+1, dp[i]);
                    }
                }
               sum=max(sum, dp[i]);
            }
            printf("%d\n", sum+1);
        }
        return 0;
    }

    还有一个错误的,因为过了不少样例,卡着我一直找不出来

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<iostream>
    using namespace std;
    #define N 10005
    int a[N], dp[N];
    
    int main()
    {
        int n, m, i, j, sum;
        while(scanf("%d", &n)!=EOF)
        {
            memset(a, 0, sizeof(a));
            memset(dp, 0, sizeof(dp));
            for(i=0;i<n;i++)
            {
                scanf("%d", &a[i]);
            }
            dp[0]=1;
            sum=0;
            for(i=1;i<n;i++)
            {
                for(j=0;j<i;j++)
                {
                    if(a[i]>a[j])
                    {
                        dp[i]=max(dp[j], dp[i]);
                    }
                }
                dp[i]++;
                sum=max(sum, dp[i]);
            }
            printf("%d\n", sum);
        }
        return 0;
    }
  • 相关阅读:
    发现一个奇怪的问题: 不能把文件取名为 con
    博客园新购服务器硬件配置
    [重要新功能]团队Blog
    [庆祝]博客园已迁至新服务器
    [公告]博客园论坛开放注册
    博客园出现了奇怪的cookie问题
    [公告]博客园聊天室试运行
    [重发]请为你喜欢的博客园杂志的名字投上一票
    [征询意见]准备采用“创作共用”协议保护大家的原创作品
    博客园期刊制作小组Blog开通
  • 原文地址:https://www.cnblogs.com/zct994861943/p/6800123.html
Copyright © 2011-2022 走看看