【Topic】Longest non-descending subsequence

Introduction

This is a very basic dp model, the simplest is O ( n 2 ) Yes, but for fast time, we have algorithms that appear O(n log n). Explained here.

explain

one, O ( n 2 )

Everyone must be able to type this with their eyes closed.
We set f[i] to denote the length of the longest subsequence taken to the i-th.
then you can N 2 Enumeration, brute force transfer: f[i]=max(f[i],f[j]+1);

2. O(n log n)

In fact, n log n is only calculated in a different way, and it is better understood than the above. We can visually see how the longest length is accumulated. (But in fact, we can't see the final sequence of this algorithm, we can only know the answer, but we can know that when there are only the first i number, the longest length of i must be selected).
The algorithm is:
① Add a number at a time. Obviously, if the number at the top of the sequence is smaller than it, it can be placed directly at the end of the queue, and the length is increased by one.
②But the problem is, if it is bigger than it, then you can only find a place in the middle where it can be stored. And this place just satisfies that the left side is less than or equal to it, and the right side is greater than or equal to it. So we get the longest length when we must select this place x.
So how to find it? Two points! Because this is a completely monotonic queue.
The final answer is the length accumulated each time.

#include<cstdio>
#include<iostream>
using namespace std;
int f[100005];
int n,a[100005];
int main()
{
    scanf("%d",&n);
    int i,j,l,r,mid;
    for (i=1;i<=n;++i)
        scanf("%d",&a[i]);
    f[0]=0;
    for (i=1;i<=n;++i)
    {
        if(a[i]>f[f[0]])
            f[++f[0]]=a[i];
        else
        {
            l=1;r=f[0];
            while(l<r)
            {
                mid=(l+r)/2;
                if(f[mid]>a[i])r=mid;
                else l=mid+1;   
            }   
            f[l]=a[i];
        }
    }
    printf("%d\n",f[0]);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326046451&siteId=291194637