EricYang

Tech Spot of Eric

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::
Longest Ordered Subsequence
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 24010   Accepted: 10407

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

Source

Northeastern Europe 2002, Far-Eastern Subregion
 
 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 using namespace std;
 5 
 6 int n;
 7 int a[1010];
 8 int b[1010];
 9 
10 // x[l]< t <=x[u], return u
11 int bSearch(int t, int end)
12 {
13     int low, mid ,high;
14 
15     low =-1;
16     high=end+1;
17 
18     while(low+1!=high)
19     {
20         mid=low+(high-low)/2;
21         if(t>b[mid])
22         {
23             low=mid;
24         }
25         else
26         {
27             high=mid;
28         }
29     }
30     if(high>=end+1 || b[high] < t)
31     {
32         return -1;
33     }
34     else
35     {
36         return high;
37     }
38 }
39 
40 int main()
41 {
42 
43     while(scanf("%d",&n)!=EOF)
44     {
45         memset(b,0,n*sizeof(int));
46         for(int i=0; i<n ;i++)
47         {
48             scanf("%d",&a[i]);
49         }
50         //dp for lis
51         b[0]=a[0];
52         int k=0;
53         for(int i=1; i<=n-1; i++)
54         {
55             if(a[i]>b[k])
56             {
57                 k++;
58                 b[k]=a[i];
59             }
60             else
61             {
62                 int pos=bSearch(a[i], k);
63                 b[pos]=a[i];
64             }
65         }
66         printf("%d\n",k+1);
67     }
68     return 0;
69 }

 

posted on 2012-08-19 22:49  Eric-Yang  阅读(211)  评论(0)    收藏  举报