Dynamic Planning-the longest descent sub-sequence in the array

Source: Internet
Author: User

----- 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;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.