Enter an n, and n data, to output the longest non-descending subsequence
Effect:
There are two ways of thinking:
1.O (n^2) idea
Use a num to record the length of the last digit with that number
With an if limit of two conditions, later greater than the preceding and the length of the back is greater than the length of the previous +1 then the description needs to be updated, and finally just traverse all the numbers in Num to see that number is the longest length of the start point. This is a better understanding.
#include <cstdio>Const intMAX = Max;intA[max],num[max];intMain () {intN; scanf ("%d",&N); for(inti =1; i<= N; i++) scanf ("%d",&A[i]); for(inti =1; I <= N; i++) {Num[i]=1; for(intj =1; J < I; J + +){ if(A[i] > A[j] &&num[i] < NUM[J] +1) Num[i]= num[j]+1; } } intMax =0; for(inti =1; I <= N; i++){ if(Max <Num[i]) Max=Bnum[i]; } printf ("%d", Max); return 0;}View Code
2.O (N*LOGN) idea
This is more difficult to understand.
Use B[k] to record the length of the subscript, and the last number is its value
B[1] = a[1], and then loop, judging whether a[i] > b[k], if so, b length is longer, the value becomes a[i], otherwise, from the length of 1 to find the length of K, because B is monotonically increasing, so in which to find more than b[j], less than b[j+1] The subscript of this value is equivalent to finding a monotone string in the same value as the N to be found, using the dichotomy, but the following mark is two points, L = mid + 1,r = mid-1, return the value of L, left closed right open.
#include <cstdio>using namespacestd;Const intMAX =1010;intA[max],b[max];intMain () {intN,k,l,r,mid; scanf ("%d",&N); for(inti =1; I <= N; i++) scanf ("%d", &A[i]); b[1] = a[1]; inti; for(i =2, k =1; I <= N; i++){ if(A[i] > B[k]) b[++k] = A[i];//B[k] stores the last digit of length k Else{L=1, r =K; while(l<= R) {//Two-point searchMid = (L + r)/2; if(B[mid] < a[i]) L = mid +1 ; Else if(B[mid] > a[i]) r = mid-1; Else Break; } B[l]=A[i]; }} printf ("%d\n", K); return 0;}View Code
lis--longest non-descending sub-sequence