LIS(二分版本)

· · 个人记录

最长不下降子序列

对于LIS问题,我们有dp做法了,但是因为它的复杂度是o(n^2),遇到较大数据会TLE,所以我们就有了二分做法,这里的时间复杂度是o(n \log n)

我们可以发现,dp时会保存一些不重要的信息,对于每一个长度的不下降子序列,只需保存它的最后一个数即可,当要插入一个数x进入长度为l的不下降子序列时,只需要对比l长度子序列的最后一个数和x的大小即可,具体方法如下:

#include<bits/stdc++.h>
using namespace std;
int n, a[100001], d[100001];
int len = 1;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n;
    for(int i=1; i<=n; i++) cin >> a[i];
    d[1] = a[1];
    for(int i=2; i<=n; i++) {
        if(a[i] >= d[len]) d[++len] = a[i];
        else {
            int tmp = upper_bound(d + 1, d + 1 + len, a[i]) - d;
            d[tmp] = a[i];
        }
    }
    cout << len << endl;
    return 0;
}