码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-10-25 11:00:22      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:函数返回   style   names   ++   strong   clu   包含   efi   bsp   

next_permutation( ) 和 prev_permutation( ) 函数基本类似,都需要用到头文件名<algorithm>

next_permutation()函数

用法:next_permutation(first,last)

作用:next_permutation()函数将 [ first , last ] 区间中的序列转换为字典序的下一个排列。如果下一个排列存在返回true,如果下一个排列不存在(即区间中包含的是字典序的最后一个排列),则该函数返回false,并将区间转换为字典序的第一个排列。

代码实现

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 //#define DEBUG(x) cerr << #x << "=" << x << endl
 8 const int maxn = 1e5 + 10;
 9 
10 int n, f[maxn];
11 int main()
12 {
13     //ios::sync_with_stdio(false);
14     cin.tie(0);
15     cin >> n;
16     for (int i = 0; i < n; i++) cin >> f[i];
17     sort(f, f + n);
18     do
19     {
20         for (int i = 0; i < n; i++) cout << f[i] << " ";
21         //cout << endl;
22         puts("");
23     }while (next_permutation(f, f + n)); 
24     return 0;
25 } 

 prev_permutation()函数

用法:prev_permutation(first,last)

作用:prev_permutation()函数将 [ first , last ] 区间中的序列转换为字典序的上一个排列。如果上一个排列存在返回true,如果上一个排列不存在(即区间中包含的是字典序的第一个排列),则该函数返回false,并将区间转换为字典序的最后一个排列。

代码实现

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 //#define DEBUG(x) cerr << #x << "=" << x << endl
 8 const int maxn = 1e5 + 10;
 9 
10 int n, f[maxn];
11 
12 int cmp(int a, int b)
13 {
14     return a > b;
15 }
16 
17 int main()
18 {
19     //ios::sync_with_stdio(false);
20     cin.tie(0);
21     cin >> n;
22     for (int i = 0; i < n; i++) cin >> f[i];
23     sort(f, f + n, cmp);
24     do
25     {
26         for (int i = 0; i < n; i++) cout << f[i] << " ";
27         //cout << endl;
28         puts("");
29     }while (prev_permutation(f, f + n)); 
30     return 0;
31 } 

 

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

标签:函数返回   style   names   ++   strong   clu   包含   efi   bsp   

原文地址:https://www.cnblogs.com/aiyi2000/p/9847845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!