Nlogn algorithm of the longest ascending subsequence

Source: Internet
Author: User

Nlogn algorithm of the longest ascending subsequence

Description:

Given an integer array, calculate the maximum length of the array to strictly increase the length of the subsequence. For example, the longest strictly increasing sub-sequence of sequence 1 2 2 4 3 is 1, 2, 4, 2, 3. Their length is 3.

Input:

The input may contain multiple test cases.
For each test case, the first input behavior is an integer n (1 <=n <= 100000): represents the length of the sequence to be input.
The second line contains n integers, representing the numbers in this array. All integers are within the int range.

Output:

For each test case, the maximum length of the sub-sequence is strictly increased.

Sample input:
44 2 1 351 1 1 1 1
Sample output:
21
AC code:
#include<stdio.h>#include<string.h>#define MAX 100000int main(void){int n,top;int num[MAX],Stack[MAX];int low,mid,high;int i;while(scanf("%d",&n)!=EOF){top=0;memset(Stack,0,sizeof(Stack));for(i=0;i<n;i++)scanf("%d",&num[i]);Stack[top]=-0xFFFFFF;for(i=0;i<n;i++){if(num[i]>Stack[top])Stack[++top]=num[i];else{low=1;high=top;while(low<=high){mid=(low+high)/2;if(num[i]>Stack[mid])low=mid+1;elsehigh=mid-1;}Stack[low]=num[i];}}printf("%d\n",top);}return 0;}

Principle: the smaller the number in the stack, the longer the substring is...

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.