2017-09-02 10:34:21
Writer:pprp
Longest ascending subsequence, specific analysis look at code: O (N^2) approach, DP thought
The code is as follows:
/*@theme: Lis longest ascending subsequence @writer:pprp@begin:10:00@end:10:15@declare complexity of O (n^2) @error:d p[i] = MAX (Dp[j]+1,dp[i]), Dp[i] = 1 initialized to 1@DATE:2017/9/2*/#include<bits/stdc++.h>using namespacestd;/*The longest ascending sub-sequence not optimized f (i) represents the length of the longest ascending subsequence of the position from head to I if (i < n && Arr[i] < Arr[n]) f (n) = max (f (i)) + 1;dp[i] is if taken to Arr[i] The longest ascending subsequence of the time*/intdp[10010],arr[10010];intMAX (intAintb) { returna > B?a:b;}intMain () {intN; while(Cin >> N &&N) {intMax =0; for(inti =0; i < N; i++) {Dp[i]=1; CIN>>Arr[i]; for(intj =0; J < I; J + +) { if(Arr[j] <Arr[i]) dp[i]= MAX (Dp[j] +1, Dp[i]); } Max=MAX (Max,dp[i]); } cout<< Max <<Endl; } return 0;}
2, using the optimization, recorded the possible selected points, recorded in the TMP array, and then from which to find
/*@theme: tmp longest ascending subsequence @writer:pprp@begin:10:00@end:14:32@declare complexity of O (n^2) @error:d p[i] = MAX (Dp[j]+1,dp[i]), Dp[i] = 1 initialized to 1@DATE:2017/9/2*/#include<bits/stdc++.h>using namespacestd;intarr[10010],tmp[10010];intLen;/*status definition: Used with the TMP array Tmp[i]: For all lis of length I, his results are the smallest possible, if the smaller the more easily be taken into the TMP element is strictly incremented State transfer: if (dp[j] = i) Tmp[i] = min (arr[j]) results Lookup--using a two-point method to find if (Tmp[i] < Arr[n] && tmp[i+1] >= arr[n]) f[n] = i+1 .... I represents the length of the /c3>*///binary lookup, binary lookup in tmp arr[i]//updating the TMP arrayvoidBisearch (intx) { intleft=1, mid,right=Len; while(left<=Right ) {Mid= (left+right) >>1; if(tmp[mid]<x) left=mid+1; Else Right=mid-1; } Tmp[left]=x;}intMain () {intN; while(Cin >> N &&N) {len=1; CIN>> arr[0]; Tmp[len]=arr[0]; for(intI=1; i<n; i++) {scanf ("%d",&Arr[i]); if(Arr[i] > Tmp[len])//if the value of arr that is current I points to is greater than the current value of TMP{len++; Tmp[len]=Arr[i]; }//Add the value of arr to the TMP array ElseBisearch (Arr[i]);//The lookup found in TMP updates it//If you use Lower_bound, that 's it://*lower_bound (tmp,tmp+len,arr[i]) = Arr[i];} printf ("%d\n", Len); } return 0;}
Lis Learning Notes (two algorithms)