全排列 next_permutation() 函数的用法

在头文件<algorithm>里面有以下代码:html

 

int a[]; do { } while(next_permutation(a,a+n));

 

 

可产生1~n的全排列有以下代码:数组

 

 1 #include <stdio.h>
 2 #include <algorithm>
 3 using namespace std;  4 int main(){  5     int n;  6     while(scanf("%d",&n)&&n){  7         int a[1000];  8         for(int i=0;i<n;i++){  9             scanf("%d",&a[i]); 10  } 11         sort(a,a+n);
12         do{ 13             for(int i=0;i<n;i++) 14                 printf("%d ",a[i]); 15             printf("\n"); 16         }while(next_permutation(a,a+n)); 17  } 18     return 0; 19 }

 

 

例如输入函数

3spa

1 0 2code

若是有sort()orm

输出为htm

0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
blog

若无ci

则输出为博客

1 0 2
1 2 0
2 0 1
2 1 0

发现函数next_permutation()是按照字典序产生排列的,而且是从数组中当前的字典序开始依次增大直至到最大字典序,在ACM International Collegiate Programming Contest, Egyptian Collegiate Programming Contest (2015)  Arab Academy for Science and Technology - Alexandria, November 6th, 2015 A题就能够采用next_permutation()。

 

原博客:https://www.cnblogs.com/My-Sunshine/p/4985366.html

相关文章
相关标签/搜索