Algorithm-to find the longest descending subsequence of an array (c + +)

Source: Internet
Author: User

To find the longest descending subsequence of an array -C + +-by chimomo////title: The longest descending subsequence of an array, for example {8, 14, 6, 2, 8, 14, 3, 2, 7, 4, 7, 2, 8, 101, 23, 6, 1, 2, 1, 1}, the longest descending subsequence of {14 。 8,3. 2,1}. Answer:scan from left to right, maintain a decreasing sequence. For each number, binary search in the decreasing sequence to see whether it can substituted.////*********************** #include <iostream> #include <cassert> #include <stack>using namespace std; int binarysearch (int *a, int ntarget, int nlen);//Find The Long EST decreasing sequence in array A of length nlen.void findlongestdecreasingsequence (int *a, int. nlen) {int *index = new in T[nlen];int *lds = new Int[nlen];index[0] = a[0]; Lds[0] = 1;int Indexlen = 1;for (int i = 1; i < Nlen; i++) {int pos = BinarySearch (index, a[i], Indexlen); Index[pos] = A [i]; Lds[i] = pos + 1;if (pos>= Indexlen) {indexlen++;}} int resultlen = indexlen;for (int i = nlen; I >= 0; i--) {if (lds[i] = = Resultlen) {index[resultlen-1] = A[i]; resultlen--;}} for (int i = 0; i < Indexlen; i++) {cout << index[i] << "";} Delete [] index;} Binary search Ntarget in array A of length nlen.int binarysearch (int *a, int ntarget, int nlen) {assert (A! = NULL && Amp Nlen > 0); int start = 0;int end = Nlen-1;while (start <= end) {int mid = (start + end)/2;if (Ntarget > A[mid]) { End=mid-1;} else if (Ntarget<a[mid]) {start=mid+1;} Else{return Mid;}} return start;} int main () {int a[] = {8, +, 6, 2, 8,, 3, 2, 7, 4, 7, 2, 8, 101,, 6, 1, 2, 1, 1};int nlen = sizeof (A)/sizeof (int); Findlongestdecreasingsequence (A, Nlen); return 0;} OUTPUT:/*14 8 7 6 2 1*/

Algorithm-to find the longest descending subsequence of an array (c + +)

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.