1)数学中组合数经常要用到全排列,这里介绍两个全排列相关的函数:
next_permutation(begin,end) 和 prev_permutation(begin,end)。
next_permutation(begin, end)输出全排列(输出当前排列的下一个排列,以字典序)
prev_permutation(begin, end)输出全排列(输出当前排列的上一个排列,以字典序)
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[3] = {2, 3 ,1};
next_permutation(a, a + 3);
for(int i = 0; i <= 2; i++) cout << a[i] << " ";
return 0;
}
输出结果:3 1 2(当前排列是 2 3 1; 下一个排列是 3 1 2;)
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[3] = {2, 3, 1};
prev_permutation(a, a + 3);
for(int i = 0; i <= 2; i++) cout << a[i] << " ";
return 0;
}
输出结果:2 1 3(当前排列是2 3 1; 上一个排列是2 1 3)
输出1 2 3 的全排列
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[3] = {1,2,3};
do
{
for(int i = 0; i <= 2; i++) cout << a[i] << " ";
cout << endl;
}while(next_permutation(a, a + 3));
return 0;
}
//若存在之后的排列,就返回true,继续循环,否则返回false
2)char类型的next_permutation
#include<bits/stdc++.h>
using namespace std;
char a[3] = {'a','b','c'};
int main()
{
do
{
for(int i = 0; i <= 2; i++) cout << a[i] << " ";
cout << endl;
}while(next_permutation(a, a + strlen(a)));
return 0;
}
/*
输出:
a b c
a c b
b a c
b c a
c a b
c b a
*/
3)string类型的next_permutation
string a = "abc";
do
{
cout << a << endl;
}while(next_permutation(a.begin(), a.end()));
4)自定义比较
next_permutation(a, a + n, cmp)
5)一道模板题
题目:https://www.luogu.com.cn/problem/P1088
code:
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e4 + 7;
int n, m;
int a[MAXN];
int main()
{
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for(int i = 1; i <= m; i++)
next_permutation(a + 1, a + 1 + n);
for(int i = 1; i <= n - 1; i++)
printf("%d ", a[i]);
printf("%d\n", a[n]);
return 0;
}
本文介绍了C++中用于生成全排列的next_permutation和prev_permutation函数,包括它们的工作原理和示例。内容涵盖不同数据类型的应用,如char和string,以及自定义比较函数的使用。同时提供了一道关于全排列的洛谷题目链接。
1855

被折叠的 条评论
为什么被折叠?



