Looking for a[1]. A[n], the maximum subsequence length can be recorded using dp[], with the state transition equation:
Dp[i] = max{dp[j]}+1, 1<=j<i,a[j]<a[i]
The time complexity of this algorithm O (n^2), the code is as follows:
int LTS (int *a,int *dp,int len) { int max=0; for (int i=0;i<=len;i++) { dp[i]=1; for (int j=0;j<i;j++) if (A[j]<a[i]) dp[i]=dp[i]> (dp[j]+1) dp[i]:(dp[j]+1); max=max>dp[i]?max:dp[i]; Rerutn Max; }
Now focus on the algorithm complexity of the O (NLOGN) algorithm.
Now we use an array d[], which makes d[len]=a[k], the array subscript is used to denote the length of the ascending subsequence, and the array value represents the value of the sequence A[k] (known Dp[k]=len).
If there is d[k]=a[i], then read into a[t], when A[t]>a[i], d[k+1]=a[t];
But generally a[t] will be greater than a lot of numbers, such as D[k-s]=a[j] (A[j]<a[j]), if we choose a[j] to compare the longest ascending subsequence is less s!! So which number should be compared? We can follow the steps below.
Initialize to make d[1]=a[1], when read into a[t], contrast a[t] and D[max] ( D[max]=a[k],max represents the length of the current maximum ascending subsequence):
1) a[t]>a[k] d[max+1]=a[t];
2) Otherwise, use the binary search in D to find the maximum number d[i] smaller than a[t], so d[i+1]=a[t].
The second step is very critical. Now we can look at an example and know why.
The maximal ascending subsequence of the sequence 1,5,2,3 is obtained. Use this algorithm to perform the following procedure:
d[1]=1;
A[2]>D[1], so d[2]=a[2]=5;
A[3]<D[2], in D to find the first two points than a[3] small d[1], so d[1+1]=a[3]=2,d[2]=2;
A[4]>D[2], so d[2+1]=a[4]=3;
Can get the maximum ascending subsequence sequence of 3!
The original d[2] for 5 was later updated to 2, if not updated then when read into the a[4]=3, then missing one! This is actually a strategy: if the series A[x] and A[y],
1) x<y
2) A[x]>a[y]
3) Dp[x]=dp[y],
When re-reading into the a[t] to choose, which one to take the best composition?
Obviously choose A[y], because the next read into the a[t], if a[x]>a[t]>a[y], then select A[x] will be missing, and select A[y] can be prevented from missing. In other words, we have to make the following sequence of readings:
d[len]=min{ A[i] | dp[i]= Len }
Find the maximum number of d[i] smaller than a[t] in D using the binary search, the code is as follows:
binary search int searchbin (int a[],int key,int len) { int low=1,high=len; while (Low<=high) { int mid= (Low+high)/2; if (A[mid]<key&&a[mid+1]>key) return mid; else if (a[mid]<key) low=mid+1; else high=mid-1; } return 0;} int LTS (int *a,int *d,int len) { d[1]=a[1]; int max_len=1; for (int i=2;i<=len;i++) { if (A[i]>d[max_len]) { d[++max_len]=a[i]; } else{ int T=searchbin (d,a[i],max_len); D[t+1]=a[i]; } } return Max_len;}
Maximal ascending sub-sequence algorithm