给出长度为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 <= S[i] <= 10^9)
Output
输出最长递增子序列的长度。
Input示例
8 5 1 6 8 2 4 5 10
Output示例
5
思路:最容易想到的是
dp[1] = a[1];
for(int i = 2; i <= n; i++) {
dp[i] = 1;
for(int j = 1; j < i; i++) {
if(a[i] > a[j])
dp[i] = max(dp[i], dp[j] + 1);
}
不过5w的数据,n2就爆了,可以想到一种nlogn的办法,dp[i]为长度为i的递增子序列中最小的那个数 。也比较好理解。
#include <bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<n;i++)
using namespace std;
const int maxn=(int)5e5+5;
int a[maxn];
vector<int> v;
int main(void) {
int n = (cin >> n, n);
rep(i,0,n) cin >> a[i];
v.push_back(a[0]);
rep(i,1,n) {
if(a[i] > v.back()) v.push_back(a[i]);
else
v[lower_bound(v.begin(),v.end(),a[i]) -v.begin()] = a[i];
}
cout << (int)v.size() <<endl;
}