POJ2533 最長有序子序列長度

這次做個動態規劃的深度複習,把思路講清楚,加深自己記憶,也方便他人。

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

題目鏈接:http://poj.org/problem?id=2533

所謂動態規劃,關鍵在於找到一個遞推公式。dp數組如下定義:

dp[i]:下標從0開始-i的最長有序子序列長度。

1 7 3 5 9 4 8對應的dp值爲:

1 2 2 3 4 3 4

dp[i]如何求得呢?從下標0-(i-1)依次與a[i]進行比較,如果a[i]>a[j],

更新dp[i],dp[i]=max(dp[i],dp[j]+1)

最後的結果不是dp[n-1],dp[i]的定義是,下標從0開始-i的最長有序子序列長度,dp[n-1]就一定是最長子序列的地方了,有可能更小。

看個例子:

1 2 3 4 5 3 2 1。顯然dp[4]纔是最大的,dp[7]反而很小。

好久沒寫oj,注意下,最後結果要換行,不讓會wa。

#include<iostream>
#include<cstdio>
#include<algorithm>//max函數頭文件
using namespace std;
#define N 1005
int a[N],dp[N];
int main()
{
    int n,longest=1;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
        dp[i]=1;
    }
    for(int i=1;i<n;i++)
    {
        for(int j=0;j<i;j++)
        {
            if(a[i]>a[j])
            {
                dp[i]=max(dp[i],dp[j]+1);
            }
        }
        longest=max(longest,dp[i]);
    }
    printf("%d\n",longest);//換行不要忘了
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章