[ACM - STL] next_permutation( ) & prev_permutation( )函数

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值