Longest Ordered Subsequence
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 24375   Accepted: 10596

Description

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

思路:

开一个栈,每次取栈顶元素top和读到的元素temp做比较,如果temp > top 则将temp入栈;如果temp < top则二分查找栈中的比temp大的第1个数,并用temp替换它。 最长序列长度即为栈的大小top。

这也是很好理解的,对于x和y,如果x < y且Stack[y] < Stack[x],用Stack[x]替换Stack[y],此时的最长序列长度没有改变但序列Q的''潜力''增大了。

举例:原序列为1,5,8,3,6,7

栈为1,5,8,此时读到3,用3替换5,得到1,3,8; 再读6,用6替换8,得到1,3,6;再读7,得到最终栈为1,3,6,7。最长递增子序列为长度4。


代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
  int x;
  int stack[100];
  stack[0]=-1;
  int top=0;
  int n;
  scanf("%d",&n);
  for(int i=0;i<n;i++)
  {
     scanf("%d",&x);
  if(x>stack[top])
  stack[++top]=x;
  else
  {
     int l=1;
  int r=top;
  while( l<=r )
  {
     int m=(l+r)/2;
     if(x > stack[m])
     l=m+1;
     else
     r=m-1;     
  }
  stack[ l ]=x; 
     }    
  }
  printf("%d\n",top);
  //system("pause");
  return 0; 
}
链接:http://poj.org/problem?id=2533