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

猜你喜欢

转载自www.cnblogs.com/cake-lover-77/p/10178428.html