Returns the longest monotonic non-descending subsequence of an array.

Source: Internet
Author: User

/*
* Enter a series of Integers to obtain the length of the longest monotonic non-descending subsequence.
* Death hunting
* 2005.12.2
*/
# I nclude <iostream>
# I nclude <vector>

Using namespace STD;

Int main ()
{
Vector <int> sequence;
Vector <int> length;
Vector <int> result;
/*
* Note that the count here should be 1, because the shortest non-descending subsequence is 1 and cannot be 0
* This is also true in subsequent cycles.
*/
Int num, I = 0, j = 0, K = 0, Count = 1, temp = 1;

/*
* Accept user input until the user input is 0
*/
Cout <"Please input your sequence" <Endl;
Cin> num;
While (num! = 0)
{
Sequence. push_back (Num );
Cin> num;
}
/*
* Perform two cycles to find the longest non-descending subsequence
In each loop, the temporary vector is cleared and the counter is set to 1.
*/
For (I = 0; I <sequence. Size (); I ++)
{
K = I;
J = I + 1;
Temp = 1;
Length. Clear ();
/*
Insert to temporary Vector
*/
Length. push_back (sequence [k]);
/*
If the sequence has two consecutive conditions: the first one is not smaller than the following one.
Continuously loops, increases counters, and inserts them into the temporary storage vector Length
*/
While (sequence [k] <= sequence [J])
{
Length. push_back (sequence [J]);
++ Temp;
++ K;
++ J;
}
/*
If the Count value is smaller than the currently found Temp value, it indicates that a subsequence longer than the Count value is found.
Assign temp to count, and assign the data stored in the current result to the value in temp.
*/
If (count <temp)
{
Count = temp;
Result. Clear ();
For (k = 0; k <length. Size (); k ++)
{
Result. push_back (length [k]);
}
}
}
Cout <"the longest nonascendent sequence of this integer sequence is:" <Endl;
Cout <count <Endl;
Cout <"the number (s) are as follows:" <Endl;
For (I = 0; I <result. Size (); I ++)
{
Cout <result [I] <"";
}
Cout <Endl;
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.