1. 程式人生 > >Longest Ordered Subsequence(最長上升子序列,dp)

Longest Ordered Subsequence(最長上升子序列,dp)

A numeric sequence of  ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence ( a1, a2, ..., aN) be any sequence ( ai1, ai2, ..., 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

簡單dp,要我們找到最長上升子序列,輸出序列的個數。
我們把第一個元素標註為dp[1]=1,說明這是這個子序列的第一個元素,然後把第二個元素與第一個元素比較,如果比1大,就標註dp[2]=2,然後把第3個元素與第1、2個元素比較,
如果比第1個小,就標記為dp[3]=0,如果比第1個大,就標記為dp[3]=2,如果比第2個小,那dp[3]=2,如果比第2個大,dp[3]=3。
例一:1 3 2,dp[1]=1,dp[2]=2,dp[3]=2
例二:3 1 2 4,dp[1]=1,dp[2]=1,dp[3]=2,d[4]=3
所以我們需要一個t去和前面元素標記的序列位置比較,每次初始t=0,t>dp[j],t=dp[j],dp[i]=t+1
 1 #include<stdio.h>
 2 #include<algorithm>
 3 using namespace std;
 4 int n,a[1010],dp[1010];
 5 int main()
 6 {
 7     while(scanf("%d",&n)!=EOF)
 8     {
 9         for(int i=1;i<=n;i++)
10             scanf("%d",&a[i]);
11         dp[1]=1;
12         for(int i=2;i<=n;i++)
13         {
14             int t=0;
15             for(int j=1;j<i;j++)
16             {
17                 if(a[i]>a[j])
18                 {
19                     if(t<dp[j])
20                     {
21                         t=dp[j];
22                     }
23                 }
24             }
25             dp[i]=t+1;
26         }
27         sort(dp+1,dp+n+1);
28         printf("%d\n",dp[n]);
29     }
30     return 0;
31 } 
View Code