C++ next_permutation()函数

本文介绍了C++中用于生成全排列的next_permutation和prev_permutation函数,包括它们的工作原理和示例。内容涵盖不同数据类型的应用,如char和string,以及自定义比较函数的使用。同时提供了一道关于全排列的洛谷题目链接。

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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值