STL source code profiling algorithm stl_algo.h -- pre_permutation

Source: Internet
Author: User

STL source code profiling algorithm stl_algo.h -- pre_permutation

 

Pre_permutation

----------------------------------------------------------------
Description: gets the first permutation and combination of the sequence marked by [first, last. If no value exists, false is returned. If yes, true is returned.
Ideas:
From the back to the front
1. Find two adjacent elements, set the left-side element to * I, and the right-side element to * ii, which meets * I> * ii
2. Find the first element smaller than * I and set it to * j. The * I and * j elements are reversed.
3. Reverse all elements on the right side of ii


Template
 
  
Bool prev_permutation (BidirectionalIterator first, BidirectionalIterator last) {if (first = last) return false; bidirealialiterator I = first; ++ I; if (I = last) return false; I = last; -- I; for (;) {BidirectionalIterator ii = I; -- I; if (* ii <* I) {// The condition for meeting * ii <* I --> next_permutation is * I <* ii BidirectionalIterator j = last; while (! (* -- J <* I); // when finding the * j <* I * j --> next_permutation, the condition is * I <* j iter_swap (I, j); reverse (ii, last); return true;} if (I = first) {reverse (first, last); return false ;}}}
 


Example:
int main(){  int A[] = {2, 3, 4, 5, 6, 1};  const int N = sizeof(A) / sizeof(int);  cout << Initially:              ;  copy(A, A+N, ostream_iterator
 
  (cout,  ));  cout << endl;  prev_permutation(A, A+N);  cout << After prev_permutation: ;  copy(A, A+N, ostream_iterator
  
   (cout,  ));  cout << endl;  next_permutation(A, A+N);  cout << After next_permutation: ;  copy(A, A+N, ostream_iterator
   
    (cout,  ));  cout << endl;}
   
  
 


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.