acwing 896 The longest ascending subsequence II (two-point monotonic optimization)

Topic

Insert picture description here

answer

  1. For the unoptimized longest ascending subsequence problem, we use f[i] to represent the longest ascending subsequence ending in i, and then enumerate the numbers before i to update f[i]. This is O(n 2 ), the data range of this question is large, and it will time out

Insert picture description here
The optimized version is actually a greedy idea. For ascending subsequences of the same length, 1 3 5 and 1 2 7 actually we only need to keep the ending numbers smaller, because the smaller the ending, the more we may update next time. For example, if the next number is 6, then 1 3 5 can be updated to 1 3 5 6, but 1 2 7 is not, so we can use an f array to record the ascending subsequence of length 1 2 3... The ending number, such as f[1]=1. We can also find that the f array is also monotonically increasing (you can prove it yourself)

  1. Then every time you enumerate a[i] from front to back, you can find a f[mid] with dichotomy, so that a[i] is the smallest value greater than f[mid], that is, f[mid+1]> a [i]> f[mid], then the length is r + 1, and then update the value at the position of f[r+1] to make it as small as possible
  1. The final len is the length of the longest ascending subsequence, enumeration O(n), bipartite O(logn), total time complexity O(nlogn)

Code

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1e5 + 10;

int n;
int a[N];
int f[N];


int main() {
    
    

    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i];

    int len = 0;
    for (int i = 1; i <= n; i++) {
    
    
        int l = 0, r = len;
        while (l < r) {
    
    
            int mid = (l + r + 1) >> 1;
            if (f[mid] < a[i]) l = mid;
            else r = mid - 1;
        }
        len = max(len, r + 1);
        f[r + 1] = a[i];
    }
    cout<<len<<endl;


    return 0;
}


Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114823416