1 int binsearch (const vector <int> & tail, int Len, int key) // 2 {3 int left = 0, Right = len-1; 4 int mid; 5 6 While (left <= right) 7 {8 Mid = left + (right-left)> 1); 9 If (tail [Mid] = key) 10 return mid; 11 else if (tail [Mid]> key) 12 Right = mid-1; 13 else14 left = Mid + 1; 15} 16 17 return left; // 18} 19 20 void Lis (int * a, int N) 21 {22 vector <int> tail (n); // end of the current subsequence, increasing 23 vector <int> orig (N); // The subscript 24 vector <int> Prev (n) at the end of the original array; // The subscript 25 int Len = 0 at the end of the current element; 26 27 tail [0] = A [0]; // 28 orig [0] = 0; 29 Prev [0] =-1; 30 + Len; 31 32 for (INT I = 1; I <n; ++ I) 33 {34 if (a [I]> tail [Len-1]) // 35 {36 tail [Len] = A [I]; // 37 orig [Len] = I; 38 Prev [I] = orig [Len-1]; 39 40 + + Len; 41} 42 else43 {44 int Pos = binsearch (tail, Len, a [I]); 45 tail [POS] = A [I]; // 46 orig [POS] = I; 47 Prev [I] = POS> 0? Orig [pos-1]:-1; 48} 49} 50 51 stack <int> STK; // 52 for (INT cur = orig [Len-1]; cur> = 0; cur = Prev [cur]) 53 {54 STK. push (A [cur]); 55} 56 57 cout <Len <Endl; 58 While (! STK. Empty () 59 {60 cout <STK. Top () <''; 61 STK. Pop (); 62} 63 cout <Endl; 64}
Algorithm question-Maximum Non-decreasing subsequence of the array