Computer >> Máy Tính >  >> Lập trình >> C ++

Chương trình C ++ để triển khai Prev_Permutataion trong STL

Prev_permutation trong STL được sử dụng để sắp xếp lại các phần tử trong phạm vi [đầu tiên, cuối cùng] thành hoán vị nhỏ hơn về mặt từ vựng trước đó. Mỗi hoán vị là một trong N! sắp xếp khả thi mà các yếu tố có thể thực hiện. Đây là một chương trình C ++ để triển khai Prev_permutation trong STL.

Thuật toán

Begin
   Define one integer array variable elements[].
   Get the number of data e from the user.
   Initialize the array elements[] with e number of data from the keyboard.
   Sort all the array elements.
   Reverse the array elements.
   Do
      show(elements) //to display the current content of the array
      while (prev_permutation(elements, elements + e))
End.

Mã mẫu

#include<iostream>
#include <algorithm>
using namespace std;
void show(int a[], int n) {
   for(int i = 0; i < n; i++) {
      cout<<a[i]<<" ";
   }
   cout<<endl;
}
int main () {
   int e, i;
   cout<<"Enter number of elements to be inserted: ";
   cin>>e;
   int elements[e];
   for (i = 0; i < e; i++) {
      cout<<"Enter "<<i + 1<<" element: ";
      cin>>elements[i];
   }
   sort (elements, elements + e);
   reverse (elements, elements + e);
   cout << "The "<<e<<"! possible permutations with ";
   cout<<e<<" elements: "<<endl;
   do {
      show(elements, e);
   }
   while (prev_permutation(elements, elements + e));
   return 0;
}

Đầu ra

Enter number of elements to be inserted: 4
Enter 1 element: 7
Enter 2 element: 6
Enter 3 element: 10
Enter 4 element: 2
The 4! possible permutations with 4 elements:
10 7 6 2
10 7 2 6
10 6 7 2
10 6 2 7
10 2 7 6
10 2 6 7
7 10 6 2
7 10 2 6
7 6 10 2
7 6 2 10
7 2 10 6
7 2 6 10
6 10 7 2
6 10 2 7
6 7 10 2
6 7 2 10
6 2 10 7
6 2 7 10
2 10 7 6
2 10 6 7
2 7 10 6
2 7 6 10
2 6 10 7
2 6 7 10