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;
    }
  • 相关阅读:
    经典算法系列二-归并排序
    经典算法系列一-快速排序
    u-boot,linux,文件系统移植笔记1
    ARM函数调用时参数传递规则
    内核移植 nand分区
    LINUX的patch文件打patch
    idea插件使用
    socket通信同步通信,异步通信
    今天学了一个很简易的测试数据库是否连接成功
    wpf中TreeView的使用
  • 原文地址:https://www.cnblogs.com/zct994861943/p/6800123.html
Copyright © 2011-2022 走看看