全排列——STL

版权声明:victor https://blog.csdn.net/qq_40155097/article/details/83413338

看见很多人用DFS
但我今天想说的是,STL教你做人
昨天我和dalao比谁的速度快
结果一个是 10.07 10.07 ,一个是 10.48 10.48
STL完胜
首先我要用一个神奇的函数
组合数学中经常用到排列,这里介绍一个计算序列全排列的函数: n e x t _ p e r m u t a t i o n ( s t a r t , e n d ) next\_permutation(start,end) ,和 p r e v _ p e r m u t a t i o n ( s t a r t , e n d ) prev\_permutation(start,end) 。这两个函数作用是一样的,区别就在于前者求的是当前排列的下一个排列,后一个求的是当前排列的上一个排列。至于这里的“前一个”和“后一个”,我们可以把它理解为序列的字典序的前后,严格来讲,就是对于当前序列 p n pn ,他的下一个序列 p n + 1 pn+1 满足:不存在另外的序列 p m pm ,使 p n < p m < p n + 1 pn<pm<pn+1 .

对于 n e x t _ p e r m u t a t i o n next\_permutation 函数,其函数原型为:

#include <algorithm>
bool next_permutation(iterator start,iterator end)

当当前序列不存在下一个排列时,函数返回false,否则返回true

我们来看下面这个例子:

#include <iostream>  
#include <algorithm>  
using namespace std;  
int main()  
{  
    int num[3]={1,2,3};  
    do  
    {  
        cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl;  
    }while(next_permutation(num,num+3));  
    return 0;  
}  

输出结果为:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
当我们把 w h i l e ( n e x t _ p e r m u t a t i o n ( n u m , n u m + 3 ) ) while(next\_permutation(num,num+3)) 中的3改为2时,输出就变为了:
1 2 3
2 1 3
由此可以看出, n e x t _ p e r m u t a t i o n ( n u m , n u m + n ) next\_permutation(num,num+n) 函数是对数组num中的前n个元素进行全排列,同时并改变 n u m num 数组的值。
另外,需要强调的是, n e x t _ p e r m u t a t i o n ( ) next\_permutation() 在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。比如,如果数组num初始化为2,3,1,那么输出就变为了:
2 3 1
3 1 2
3 2 1
此外, n e x t _ p e r m u t a t i o n n o d e , n o d e + n , c m p next\_permutation(node,node+n,cmp) 可以对结构体 n u m num 按照自定义的排序方式 c m p cmp 进行排序。
现在我们就可以开始了
先贴代码:

#include<algorithm>
#include<cstdio>
using namespace std;
int main()
{
//freopen("fuck.in", "r", stdin);
//freopen("fuck.out", "w", stdout);
int n;
scanf("%d",&n);
int a[n + 5];
for(int i = 0; i <= n - 1;i++) 
a[i] = i + 1;
do 
{
for(int i = 0;i <= n - 1;i++)
printf("%5d",a[i]);
printf("\n"); 
}while(next_permutation(a,a + n)); //函数的运用
return 0//fclose(stdin);
//fclose(stdout);
}

猜你喜欢

转载自blog.csdn.net/qq_40155097/article/details/83413338