next_permutation
2016-06-10 15:52
295 查看
题目:
For example, if we have two ‘0’s and two ‘1’s, we will have a set with 6 different strings, {0011, 0101, 0110, 1001, 1010, 1100}, and the 4th string is 1001.
输入是t:测试次数, n:0的个数, m:1的个数, k:第几个数
如:a[4]={1,2,3,4}.next_permutation(a,a+4) 即为1,2,4,3.
若为4,3,2,1.next_permutation的返回值即为false,因为没有下一个排列。但是经过一次函数调用之后会变为1,2,3,4.
测试样例:
3
2 2 2
0101
2 2 10
Impossible
4 7 4
00011101111
输出结果为:
4321
4312
4231
4213
4132
4123
3421
3412
3241
3214
3142
3124
2431
2413
2341
2314
2143
2134
1432
1423
1342
1324
1243
1234
For example, if we have two ‘0’s and two ‘1’s, we will have a set with 6 different strings, {0011, 0101, 0110, 1001, 1010, 1100}, and the 4th string is 1001.
输入是t:测试次数, n:0的个数, m:1的个数, k:第几个数
1. next_permutation(在头文件algorithm中)
//用了next_permutation //注意do - while循环和直接while循环 //do-while首先执行了一次再进行while中条件的判定 //相应的还有prev_permutation //prev_permutation和next_permutation求的是全序排列 #include<iostream> #include<algorithm> // 包含next_permutation的头文件 using namespace std; int main() { int t; cin >> t; while (t--) { int n, m, k; cin >> n >> m >> k; int arr[17]; for (int i = 0; i < n; ++i) arr[i] = 0; for (int i = n; i < n + m; ++i) arr[i] = 1; int count = 0; do { count += 1; if (count == k) { for (int i = 0; i < n + m; ++i) cout << arr[i]; cout << endl; break; } } while (next_permutation(arr, arr + n + m)); if (k > count) cout << "Impossible" << endl; } return 0; }
如:a[4]={1,2,3,4}.next_permutation(a,a+4) 即为1,2,4,3.
若为4,3,2,1.next_permutation的返回值即为false,因为没有下一个排列。但是经过一次函数调用之后会变为1,2,3,4.
测试样例:
3
2 2 2
0101
2 2 10
Impossible
4 7 4
00011101111
2. prev_permutation
#include<iostream> #include<algorithm> using namespace std; int main() { int test[10]; for (int i = 4; i > 0; --i) test[4 - i] = i; do { for (int i = 0; i < 4; i++) cout << test[i]; cout << endl; } while (prev_permutation(test, test + 4)); }
输出结果为:
4321
4312
4231
4213
4132
4123
3421
3412
3241
3214
3142
3124
2431
2413
2341
2314
2143
2134
1432
1423
1342
1324
1243
1234
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性