您的位置:首页 > 其它

排列(permutation)2_6

2016-07-13 12:27 260 查看
在STL中,用来计算排列组合的函数有 next_permutation()
和 prev_permutation() ,包含在头文件#include <algorithm>。前者是求出下一个排列组合,而后者是求出上一个排列组合。所谓“下一个”和“上一个”,书中举了一个简单的例子:对序列 {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}没有下一个元素。

他们的使用方法如下:

#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;

int main(){
FILE *fin, *fout;
fin = stdin;
fout = stdout;
fout = fopen("permutationout.txt", "wb");
int d[]={1,2,3,4,5,6,7,8,9};//!
do{
int a=d[0]*100+d[1]*10+d[2];
int b=d[3]*100+d[4]*10+d[5];
int c=d[6]*100+d[7]*10+d[8];
if(c==3*a && b==2*a) fprintf(fout, "%d %d %d\n", a, b, c);
}while(next_permutation(d,d+9));//!

int d[]={9,8,7,6,5,4,3,2,1};//!
do{
int a=d[0]*100+d[1]*10+d[2];
int b=d[3]*100+d[4]*10+d[5];
int c=d[6]*100+d[7]*10+d[8];
if(c==3*a && b==2*a) fprintf(fout, "%d %d %d\n", a, b, c);
}while(prev_permutation(d,d+9));//!
fclose(fout);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息