Longest ascending subsequence I (LIS)

Subject link
https://www.acwing.com/problem/content/897/

Idea
Yan's dp analysis method, the Insert picture description here
      state shown in the above figure has been explained in the figure. Regarding the state division, f [i] represents the collection of all ascending subsequences ending with the i-th number, so all elements of this collection must be It ends with the i-th number. Our division is a bit similar to the backpack. According to which number is the (i-1)th number to classify, it can be divided into:
      there is no (i-1)th number, and the sequence length is 1. , Represented by 0.
      The (i-1)th number is the first number, represented by 1.
      …
      The (i-1)th number is the jth number, denoted by j.
      …
      The (i-1)th number is the (i-1)th number, represented by (i-1).
      Note that the (i-1)th number mentioned above does not mean the previous number of the i-th number in the original sequence, it is the longest ascending subsequence represented by each i-th number represented by f [i] The previous number, and then this number corresponds to which number in the original sequence.
      Of course, every category in it does not necessarily exist. If a [j] ≥ a [i ], then this category does not exist. Of course, we can put them all here. If it does not exist, just judge and ignore it. Just take a max if it exists.
      So how do we ask for what exists? In fact, it is very simple. When you reach the i-th number, the previous (i-1) state must have been calculated. For f [i ], it is f [j] + 1 (this 1 is added a [i] itself), then take a max for f [i] and (f [j] + 1), the time complexity is O(n²), and finally traverse the f array to find the maximum value, because we don’t Knowing who ends with will be the maximum.
      This is the simple approach of LIS, and it also has a binary optimized version that can further reduce time complexity. The code for the simple approach is posted below. ( I haven’t fully understood the binary optimization yet )

Code

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

int a[1005];
int f[1005];
int n;

int main()
{
    
    
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
    
    
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=n;i++)
    {
    
    
        f[i]=1;
        for(int j=1;j<i;j++)
        {
    
    
            if(a[i]>a[j])
            {
    
    
                f[i]=max(f[i],f[j]+1);
            }
        }
    }
    int res=0;
    for(int i=1;i<=n;i++) res=max(res,f[i]);

    printf("%d\n",res);
    return 0;
}

Guess you like

Origin blog.csdn.net/Star_Platinum14/article/details/113101397