DP模型:

d(i) 以第 i 个元素结尾的最长递增子序列的长度。

那么就有 d(i) = max(d(j)) + 1;(j<i&&a[j]<a[i]),答案 max(d(i)); 时间复杂度为 O(n*n);

 

下面介绍一个用二分优化的O(nlogn)的算法。

用一个数组g[i] 表示 d 值为 i 的数的最小的 a;即 最长递增子序列为 i 时,最小的 a 是多少。

最长递增子序列LIS再谈

显然 g[i]<=g[2]<=g[3];

计算d[i] : 需要找到 g中大于等于a[i] 的第一个数 j ,d[i] = j;

更新g :     g[j] = a[i] ;

使用STL的lower_bound可以直接求出比a[i] 大的第一个数,用的二分查找实现,总时间O(nlogn);

 

#include <bits/stdc++.h>
using namespace std;

int a[1005];
int b[1005];

int main()
{

    int n;
    scanf("%d",&n);

    for(int i=0;i<n;i++)
        scanf("%d",&a[i]);

    int len = 1;
    b[0] = a[0];

    for(int i=1;i<n;i++) {
        if(a[i]==b[len-1])
            continue;
        if(a[i]>b[len-1])
            b[len++] = a[i];
        else {
            int pos = lower_bound(b,b+len,a[i])-b;
            b[pos] = a[i];
        }
    }

    printf("%d\n",len);
    return 0;
}
View Code

相关文章:

  • 2021-10-09
  • 2021-10-28
  • 2021-10-16
  • 2021-08-22
  • 2022-12-23
  • 2021-05-22
  • 2021-11-09
  • 2022-12-23
猜你喜欢
  • 2021-12-27
  • 2021-11-20
  • 2021-07-07
  • 2022-01-01
  • 2021-07-30
  • 2022-12-23
  • 2021-07-30
相关资源
相似解决方案