Problem description: Find the longest descending subsequence of an array, for example, {9, 4, 3, 2}. The longest descending subsequence is {9, 5, 4, 3, 2 }.
Idea: this is a classic problem that can be solved using dynamic planning. Assume that the source array is a and a secondary array is B. B [I] indicates the length of the longest descending sequence ending with a [I. For example, if a [I] is greater than all the previous elements, B [I] = 1.
With this auxiliary array, we can introduce the following recursive formula. B [I]
= Max {B [k] + 1, a [k]> A [I] & 0 = <k <I}, B [0] = 1. The maximum length of the descending sequence is max {B [I], 0 <= I <n }. Of course, the results must be printed out. How can we obtain this sequence? This is an inverse process. If we know that B [k] is the largest, a [k] is the end element of the longest descending sequence. The key is to obtain the previous element. We can search for the element before B [k] (from the back to the back ), when B [I] + 1 = B [k] & A [I]> A [k] is satisfied, a [I] is the previous element and can be solved recursively. The time complexity of the algorithm is O (n ^ 2). There is also a solution on the Internet. The complexity is O (nlogn ). If you are interested, you can search for it. If you have a limited level of understanding, you will not reference it here.
Reference code:
// Function: print the longest decreasing sub-sequence // function parameter: parray points to the source array, Pb points to the auxiliary array, and K indicates the end element of the longest largest sequence // return value: no void print (int * parray, int * pb, int K) {for (INT I = k-1; I> = 0; I --) {If (Pb [k] = Pb [I] + 1 & parray [I]> parray [k]) // reproduce the process of dynamic programming, it is just a reverse {print (parray, Pb, I); break ;}} cout <parray [k] <'';} // function: maximum descent sub-sequence of an array // function parameter: parray refers to the source array, Len indicates the array length // return value: no void findmds (int * parray, int Len) {int I, j, Maxi = 0; // Maxi is used to record the end element int * pb = new int [Len] of the longest descending sequence; // auxiliary space, pb [I] indicates the longest descending sequence length ending with paray [I] for (I = 0; I <Len; I ++) // initialize Pb [I] = 0; for (I = 0; I <Len; I ++) // calculates the longest descending sequence ending with paray [I] {Pb [I] = 1; for (j = 0; j <I; j ++) {If (parray [J]> parray [I] & Pb [J] + 1> Pb [I]) // This attention formula is critical {Pb [I] = Pb [J] + 1; if (Pb [I]> Pb [Maxi]) // update the longest descending sequence currently found Maxi = I ;}} print (parray, Pb, Maxi); // print the target sequence Delete [] Pb ;}
I enjoy the copyright of blog articles, reprint please indicate the source http://blog.csdn.net/wuzhekai1985