1. 程式人生 > >DPL_1_D Longest Increasing Subsequence dp+二分查詢 最長遞增子序列

DPL_1_D Longest Increasing Subsequence dp+二分查詢 最長遞增子序列

For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A.

An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik.

Input

n
a0
a1
:
an-1

In the first line, an integer n is given. In the next n lines, elements of A are given.

Output

The length of the longest increasing subsequence of A.

Constraints

  • 1 ≤ n ≤ 100000
  • 0 ≤ ai ≤ 109

Sample Input 1

5
5
1
3
2
4

Sample Output 1

3

Sample Input 2

3
1
1
1

Sample Output 2

1

n^2複雜度的演算法過不了此題。。。

需要dp+二分過。。。

程式碼如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=100005;
int n;
int a[maxn];
int dp[maxn];
int Max;
void init()
{
   Max=1;
   dp[0]=a[0];
}
int main()
{
    scanf("%d",&n);
    for (int i=0;i<n;i++)
        scanf("%d",&a[i]);
    init();
    for (int i=1;i<n;i++)
    {
        if(dp[Max-1]<a[i])
            dp[Max++]=a[i];
        else
            *lower_bound(dp,dp+Max,a[i])=a[i];
    }
    printf("%d\n",Max);
    return 0;
}