Longest Ordered Subsequence POJ - 2533(动态规划)

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

思路:

动态规划,求出最长递增子序列的长度,假设要求arr[0~i]这一区间内的最长子序列长度,只要求出离i最近且最长的递增子序列长度,再+1即可(这个1是加上arr[i]这一个元素),由于i左边的数的最长子序列都已经求出,所以只要找到i左边比i小的数j,那么j之前生成的最大递增子序列里面的各个元素一定都小于i,要找到最大的L[i]就要找出最大的L[j],因此只要找到一个j比i小,就判断L[j]是否比当前的max值大,如果是就更新max值。

#include <iostream>
using namespace std;
int Max;
int L[1005];
int arr[1005];
void LOS(int n)
{
    for(int i=0; i<n; i++)
    {
        L[i]=1;    //初始化,每个字符的最长增长子序列是自己本身
    }
    for(int i=1; i<n; i++)
    {
        Max=1;
        for(int j=i-1; j>=0; j--)    //j=i-1所以i从1开始
        {
            if(arr[j]<arr[i]&&Max<L[j]+1)    //逆序遍历,寻找第i个字符前是否有小于它的字符,若有则L[i]=L[j]+1(因为j总是尽可能离i近,所以每找到一个也就只能+1),否则L[i]不作改动
            {
                Max=L[j]+1;
                L[i]=Max;
            }
        }
    }
}
int main()
{
    int n,index=0;
    while(cin>>n)
    {

        for(int i=0; i<n; i++)
        {
            cin>>arr[i];
        }
        LOS(n);
        for(int i=1; i<n; i++)
        {
            if(L[i]>L[index])    //找出最长子序列所在的下标
            {
                index=i;
            }
        }
        cout<<L[index]<<endl;
    }
    return 0;
}
发布了35 篇原创文章 · 获赞 2 · 访问量 1394

猜你喜欢

转载自blog.csdn.net/weixin_41001497/article/details/89338458