STL::next_permutation();

     next_permutation()可以按字典序生成所给区间的全排列。

     在STL中,除了next_permutation()外,还有一个函数prev_permutation(),两者都是用来计算排列组合的函数。前者是求出下一个排列组合,而后者是求出上一个排列组合。所谓“下一个”和“上一个”,书中举了一个简单的例子:对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比bc都小,c比b大,它的下一个序列即为{a, c, b},而{a, c, b}的上一个序列即为{a, b, c},同理可以推出所有的六个序列为:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}没有上一个元素,{c, b, a}没有下一个元素。

        next_permutation()和prev_permutation()包含在头文件#include <algorithm>中。

 

        注意:虽然最后一个排列没有下一个排列,用next_permutation()会返回false,但是使用了这个方法后,序列会变成字典序列的第一个,如cba变成abc。prev_permutation同理。

 

用法:

这里我们举例0,1,2,3,4的全排列。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 int main(){
 5     int a[5]={0,1,2,3,4};
 6     int ans=0;
 7     while(ans<20){
 8         next_permutation(a,a+5);
 9         for(int i=0;i<5;i++){
10             cout<<a[i];
11         }
12         cout<<endl;
13         ans++;
14     }
15     return 0;
16 }

输出结果:

 

对于prev_permutation():

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 int main(){
 5     int a[5]={0,1,2,3,4};
 6     int ans=0;
 7     while(ans<20){
 8         prev_permutation(a,a+5);
 9         for(int i=0;i<5;i++){
10             cout<<a[i];
11         }
12         cout<<endl;
13         ans++;
14     }
15     return 0;
16 }

 

输出结果:

 

例题参考:POJ-2718POJ-3187

posted @ 2017-07-27 10:04  Kiven#5197  阅读(449)  评论(0编辑  收藏  举报