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...