next_permutation( ) 和 prev_permutation( ) 函数基本类似,都需要用到头文件名
next_permutation()函数
用法:next_permutation(first,last)
作用:next_permutation()函数将 [ first , last ] 区间中的序列转换为字典序的下一个排列。如果下一个排列存在返回true,如果下一个排列不存在(即区间中包含的是字典序的最后一个排列),则该函数返回false,并将区间转换为字典序的第一个排列。
代码实现
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
//#define DEBUG(x) cerr << #x << "=" << x << endl
const int maxn = 1e5 + 10;
int n, f[maxn];
int main()
{
//ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) cin >> f[i];
sort(f, f + n);
do
{
for (int i = 0; i < n; i++) cout << f[i] << " ";
//cout << endl;
puts("");
}while (next_permutation(f, f + n));
return 0;
}
prev_permutation()函数
用法:prev_permutation(first,last)
作用:prev_permutation()函数将 [ first , last ] 区间中的序列转换为字典序的上一个排列。如果上一个排列存在返回true,如果上一个排列不存在(即区间中包含的是字典序的第一个排列),则该函数返回false,并将区间转换为字典序的最后一个排列。
代码实现
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
//#define DEBUG(x) cerr << #x << "=" << x << endl
const int maxn = 1e5 + 10;
int n, f[maxn];
int cmp(int a, int b)
{
return a > b;
}
int main()
{
//ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) cin >> f[i];
sort(f, f + n, cmp);
do
{
for (int i = 0; i < n; i++) cout << f[i] << " ";
//cout << endl;
puts("");
}while (prev_permutation(f, f + n));
return 0;
}