练习题2

                    Longest Ordered Subsequence

Problem description

 

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 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 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

题目解释

给一个无序数列,找出其中的最长的上升子序列

方法一:结构体

AC代码

#include
#include
using namespace std;
struct digital{
    int num;
    int max1;
};
bool compare(digital a,digital b)
{
    return a.max1>b.max1;
} 
int main()
{
    int n;
    while(cin>>n)
    {
        digital a[n];
        for(int i=0;i)
        {
            cin>>a[i].num;
            a[i].max1=1;
        }
        for(int i=0;i)
        {
            int max0=0;
            for(int j=0;j)
            {
                if(a[i].num>a[j].num&&max0<a[j].max1)
                {
                    max0=a[j].max1;
                }
            }
            a[i].max1+=max0;
        }
        sort(a,a+n,compare);
        cout<0].max1<<endl;
    } 
    return 0;
}

方法二:dp

AC代码

#include
using namespace std;
int dp[100010];
int a[100010];
int main()
{
    int N;
    while (scanf("%d",&N)!=EOF)
    {
        int ans = 0;
        for (int i = 0; i < N; i++)
            scanf("%d", &a[i]);
        for (int i = 0; i < N; i++)
        {
            dp[i] = 1;
            for (int j = 0; j < i; j++)
                if (a[i] > a[j])
                    dp[i] = max(dp[i], dp[j] + 1);
            ans = max(ans, dp[i]);
        }
        printf("%d\n", ans);
    }
    return 0; 
}

 

 

 

 

转载于:https://www.cnblogs.com/liyou555/p/11503011.html

你可能感兴趣的:(练习题2)