Full arrangement template non-template

1.
There is a function next_permutation(start,end) in the algorithm library of template C++. The role is to find the next permutation of a sort, you can traverse all permutations. Note that if it does not end, the loop will continue, and the result will appear the same arrangement. The opposite function is prev_permutation(start,end), which is a function to find the previous permutation of a sort.

For the next_permutation function, its function prototype is:

include

bool next_permutation(iterator start, iterator end)
// When there is no next permutation in the current sequence, the function returns false, otherwise it returns true.

#include<bits/stdc++.h>
using namespace std;
int n;	// n表示序列中数的个数
int a[10005];
int main() 
{
    
    
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	do
	{
    
    
		for (int i = 0; i < n; i++)  // 打印
			cout << a[i] << " ";
		cout << endl;
	}while (next_permutation(a, a + n));
	return 0;
}

It should be emphasized that next_permutation() needs to sort the array to be arranged in ascending order before using it, otherwise it can only find out the total number of permutations after the sequence.


A sample question corresponding to the non-template //z code

#include<bits/stdc++.h>
int cnt=0;
using namespace std;
typedef long long ll;
const int maxn=1e6+199;
int len1,len2,len3;
ll a[maxn];
int k,n,m;
void dop()
{
    
    

    for (k = n - 1; k >= 1; k--)
	{
    
    
		if (a[k] < a[k + 1])   //找到最后可增加的位,即定位 
			break;
	}
	for (int i = n; i > k; i--)
	{
    
    
		if (a[i] > a[k])
		{
    
    
			swap(a[i], a[k]);  //找到最小可增加的数字 交换
			break;
		}
	}
	sort(a + k + 1, a + n + 1);   //对后面的升序排列
}
int main(){
    
    
  cin>>n;
  cin>>m;
  for(int i=1;i<=n;i++)
    cin>>a[i];
  int i=0;
 while(i<m)
 {
    
    
     i++;
     dop();
 }
 for(int i=1;i<=n;i++)
 {
    
    
     if(i==1)
        cout<<a[i];
     else
        cout<<' '<<a[i];
 }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_52172364/article/details/113248093