next_permutation

本文通过两个示例介绍了如何使用C++标准库中的`next_permutation`和`prev_permutation`函数来生成字符串的所有可能排列。第一个示例演示了如何找出特定位置的排列,而第二个示例则展示了如何逆序生成所有排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值