----- Edit by ZhuSenlin HDU
Returns the longest descending subsequence of an array, for example, {9, 4, 3, 2}. The longest descending subsequence is {9, 5, 4, 3, 2}
Analysis: a typical dynamic planning question is used to calculate the maximum number of descending subsequences starting from each number and place them in a ing table. For example, for Array a [n ],
......
Then, the elements in the original array are obtained using the obtained ing table and the maximum number of subsequences. For {9, 4, 3, 2, 5, 4, 3, 2}, the maximum number of subsequences is nMaxLen = 5, and the table is pTable = }. So in pTable to find nMaxLen, nMaxLen-1 ,..., The value of the original array corresponding to 1 is the maximum decreasing subsequence. Corresponding to {9, 5, 4, 3, 2}. complexity is O (n2)
The Code is as follows:
#include <iostream>#include <cstring>using namespace std;int Fun(int aIn[],int pTable[],int nLen){int nMaxLen = 0;for(int i = nLen-1; i >= 0; --i) {int nMax = 0;for(int j = i+1; j < nLen; ++j) {if(aIn[j] < aIn[i]) {nMax = nMax < pTable[j] ? pTable[j] : nMax;}}pTable[i] = 1+nMax;nMaxLen = nMaxLen<pTable[i] ? pTable[i] : nMaxLen;}return nMaxLen;}void PrintMaxSubsequence(int aIn[], int pTable[], int nMaxLen, int nLen){for(int i = 0,j=0; i < nLen; ++i) {if(pTable[i] == nMaxLen){cout << aIn[i] << " ";nMaxLen--;}}cout << endl;}
The test code is as follows:
int main(){int aIn[] = {9,4,3,2,5,4,3,2};int nLen = sizeof(aIn)/sizeof(int);int* pTable = new int[nLen];memset(pTable,0,nLen*sizeof(int));int nMaxLen = Fun(aIn,pTable,nLen);cout << nMaxLen << endl;PrintMaxSubsequence(aIn,pTable,nMaxLen,nLen);delete [] pTable;return 0;}