您的位置:首页 > 编程语言 > C语言/C++

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:第几个数

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++