STL next_permutation(全排列算法)

来源:互联网 发布:mysql导出所有数据库 编辑:程序博客网 时间:2024/05/17 01:18
#include <iostream>     // std::cout#include <algorithm>    // std::next_permutation, std::sortint main () {  int myints[] = {1,2,3};  std::sort (myints,myints+3);  std::cout << "The 3! possible permutations with 3 elements:\n";  do {    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';  } while ( std::next_permutation(myints,myints+3) );  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';  return 0;}


Output:

The 3! possible permutations with 3 elements:
1 2 31 3 22 1 32 3 13 1 23 2 1After loop: 1 2 3


同理这个可以直接按字符串来输入输出:

#include<iostream>#include<cstring>#include<algorithm>using namespace std;int main(){char a[2000];cout<<"输入的数为:";cin>>a;cout<<"输出为:"<<endl;do{cout<<a<<endl;}while(next_permutation(a,a+strlen(a)));return 0;}


然后下面有一个例题,来更好地理解一下这个函数:

n个人排成一队,队头的人编号为1,后面的人编号分别为2,3,…,n. 1号人前面没有人,i号人的前面是i-1。 现在Kim想让这n个人重新排队,要求重新排队后编号为i的人前面不能是i-1。问有多少种排队的方法。

这个题假设n在10以内(这个例子只是用来理解next_permutation)

#include<iostream>#include<cstring>#include<algorithm>using namespace std;int a[100];int main(){int n;cin>>n;for(int i=0;i<n;i++)  a[i]=i+1;int sum=0;while(next_permutation(a,a+n)){int flag=0;for(int i=1;i<n;i++){if(a[i]==a[i-1]+1){flag=1;break;}}if(flag)  continue;else sum++;}cout<<sum<<endl;}
这个首先如果n=5,数列a的顺序是1 2 3 4 5.不满足题意,所以sum初值是0,然后next_permutation就会按着字典序输出a数组的下一个顺序.知道全部输入完为止.

0 0
原创粉丝点击