1. 程式人生 > >最長遞增子序列 (dp)

最長遞增子序列 (dp)

給出長度為N的陣列,找出這個陣列的最長遞增子序列。(遞增子序列是指,子序列的元素是遞增的)
例如:5 1 6 8 2 4 5 10,最長遞增子序列是1 2 4 5 10。
Input
第1行:1個數N,N為序列的長度(2 <= N <= 50000)
第2 - N + 1行:每行1個數,對應序列的元素(-10^9 <= Sii <= 10^9)
Output
輸出最長遞增子序列的長度。
Sample Input
8
5
1
6
8
2
4
5
10
Sample Output

5

nlogn的做法(二分)

AC程式碼:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<queue>
#include<set>
#include<vector>
#include<map>
#include<stack>
#include<cstdlib>
using namespace std;
typedef long long ll;
ll a[55000];
ll dp[55000];
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
        scanf("%lld",&a[i]);
    dp[0]=a[0];
    int l=0,r,mid,len=1;
    for(int i=1;i<n;i++){
        l=0;
        r=len;
        while(l<r){
            mid=(l+r)/2;
            if(dp[mid]<a[i])l=mid+1;
            else r=mid;
        }
        dp[l]=a[i];
        if(l>=len)len++;
    }
    printf("%d\n",len);
	return 0;
}