The LIS template

Source: Internet
Author: User

Code from someone else's blog

First, a relatively simple version

const int MAXN = 1010;
int n;
int A[MAXN];
int DP[MAXN];

int lis ()
{
    memset (DP, 0, sizeof (DP));
    int Max;
    for (int i = 0; i < n; ++i)
    {
        Max = 0;
        for (int j = 0; J < i; ++j)
        {
            if (A[i] > A[j])
            {
                max = max (max, dp[j]);
            }
        }
        Dp[i] = Max + 1;
    }
    Max = 0;
    for (int i = 0; i < n; ++i)
    {
        if (Dp[i] > Max)    max = Dp[i];
    }
    return Max;
}

And then it's the usual N*LOGN algorithm.

const int MAXN = 1010;
int n;
int A[MAXN];
int DP[MAXN];

int lis ()
{
    memset (DP, 0, sizeof (int) *n);
    int len = 1;
    Dp[0] = a[0];
    for (int i = 1; i < n; ++i)
    {
        int pos = Lower_bound (DP, DP + LEN, A[i])-DP;
        Dp[pos] = A[i];
        Len = max (len, pos + 1);
    }
    return len;
}

Above are the maximum ascending subsequence sequences that are to be strictly incremented.
If the title is deformed if the maximum ascending subsequence is to be obtained, I will give a template myself, the giant teaches me

int calc (int sign)
{
    fill (dp,dp+maxn,inf);
    int ans = 0;
    for (int i=0;i<n;i++) {
        int index = upper_bound (dp,dp+ans,a[i]*sign)-dp;//This is a non-strict sequence, if strictly required Lower_bound
        Dp[index] = a[i]*sign;
        ans = max (ans,index+1);
    }
    return ans;
}


int Lins ()
{
    return calc (1);//Ascending
}

int lnds ()
{
    return calc (-1);//Descent
}

Refueling ~ ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.