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
- STL next_permutation(全排列算法)
- STL全排列算法next_permutation和prev_permutation
- STL库全排列算法next_permutation
- STL next_permutation 全排列
- [STL]next_permutation全排列
- 全排列(STL next_permutation)
- next_permutation全排列算法
- next_permutation(全排列算法)
- next_permutation(全排列算法)
- STL实现全排列 next_permutation
- STL中的全排列next_permutation
- 枚举全排列 STL next_permutation
- HDU1716 -- 全排列 -- STL -- next_permutation()
- 用STL的next_permutation算法实现全排列
- 全排列递归算法与STL:next_permutation()函数
- STL 排序算法之全排列sort和next_permutation
- STL的排列算法next_permutation
- 全排列生成算法:next_permutation
- 【STL】STL空间配置器
- elasticsearch判断索引是否存在
- QT的 QButton 添加ICO 以及添加菜单 Action
- 16 - 12 - 11 HDU 1021 ---Fibonacci Again
- 数据绑定
- STL next_permutation(全排列算法)
- Java多线程——基本概念
- Hadoop 2.7.2集群安装配置
- Python's basics
- (2)电子商务安全知识
- 第五章
- CPUID指令
- WinAPI NET登录与共享映射
- bzoj1305 [CQOI2009]dance跳舞