枚举排列
2011-06-12 10:40
253 查看
1. 1-N 全排列
2. 可重集的排列
方法1: 递归枚举
方法2: next_permutation
运行结果:
#include <iostream> using namespace std; #define N 1001 int rcd ; int used ; int num ; int n; void permutation(int l) { if(l == n) { for(int i = 0; i < n; i++) { cout << rcd[i] << " "; } cout << endl; } else { for(int i = 0; i < n; i++) { if (!used[i]) { used[i] = 1; rcd[l] = num[i]; permutation(l + 1); used[i] = 0; } } } } int readData() { int i; if( scanf("%d", &n) == EOF) { return 0; } for(int i = 0; i < n; i++) scanf("%d", &num[i]); for(int i = 0; i < n; i++) used[i] = 0; return 1; } int main() { while(readData()) { permutation(0); } }
2. 可重集的排列
方法1: 递归枚举
#include <iostream> using namespace std; #define N 1001 int rcd ; int used ; int num ; int n; int m; void unrepeatPermutation(int l) { if(l == n) { for(int i = 0; i < n; i++) { cout << rcd[i] << " "; } cout << endl; } else { for(int i = 0; i < m; i++) { if (used[i] > 0) { used[i]--; rcd[l] = num[i]; unrepeatPermutation(l + 1); used[i]++; } } } } int readData() { int i, j, val; if( scanf("%d", &n) == EOF) { return 0; } m = 0; for(int i = 0; i < n; i++) { scanf("%d", &val); for(j = 0; j < m; j++) { if(num[j] == val) { used[j]++; break; } } if(j == m) { num[m] = val; used[m] = 1; m++; } } return 1; } int main() { while(readData()) { unrepeatPermutation(0); } }
方法2: next_permutation
// next_permutation #include <iostream> #include <algorithm> using namespace std; int main () { int myints[] = {1,1,2}; cout << "The possible permutations with 3 elements:/n"; sort (myints,myints+3); do { cout << myints[0] << " " << myints[1] << " " << myints[2] << endl; } while ( next_permutation (myints,myints+3) ); return 0; }
运行结果:
The possible permutations with 3 elements: 1 1 2 1 2 1 2 1 1
相关文章推荐
- Water Gate Management(二进制枚举组合排列模板 n个数的子集)
- 枚举排列问题
- 枚举排列
- hdu5727 枚举排列 + 二分图匹配
- 【POJ2718】Smallest Difference(枚举排列)
- UVaLive 7360 Run Step (排列组合,枚举)
- 【枚举】bzoj1072 [SCOI2007]排列perm
- 枚举排列
- 枚举排列
- Water Gate Management(二进制枚举组合排列模板 n个数的子集)
- 算法竞赛入门经典读书笔记(三)7.2枚举排列
- 按照字典序枚举排列
- 暴力求解法之枚举排列
- poj 3311 Hie with the Pie ,floyd + 枚举排列
- poj 2585 Window Pains 暴力枚举排列
- 枚举排列各种思路代码
- 杭电1015——Safecracker(dfs、递归枚举排列)
- Water Gate Management(二进制枚举组合排列模板 n个数的子集)
- UVa 1523 Helicopter 解题报告(枚举排列)
- nyoj 擅长排列的小明 II 469 (枚举找规律) 水