题目描述
输入一个序列,输出其下一个字典序的排列
如:输入1 2 3,
下一个为1 3 2,
下一个为2 1 3,
下一个为2 3 1,
下一个为3 1 2,
下一个为3 2 1(最大的字典序排列)
下一个为1 2 3(重新返回最小的字典序排列)
......
输入有多种类型:
C:表示char型数据
I:表示int型数据
D:表示double型数据
S:表示string型数据
输入
第1行:一个整数n,表示测试次数
以下n行:每行为 C/I/D/S k ...k个数据(用空格分隔)
输出
对每个测试数据输出其下一个字典序排列
IO模式
本题IO模式为标准输入/输出(Standard IO),你需要从标准输入流中读入数据,并将答案输出至标准输出流中。
输入样例
4
C 6 a b d c f e
I 4 1 2 3 4
D 2 4.3 2.1
S 4 ho ha he he
输出样例
a b d e c f
1 2 4 3
2.1 4.3
ho he ha he
碎碎念
题目说可以用next_permutaion函数,这个函数的头文件是algorithm,参数是进行操作的数组的起始位置和终止位置,返回布尔值,如果存在下一个排列的话返回true,否则返回false,也就是当前的排列最大,比如说对于数组{1,2,3},如果当前数组为{3,2,1},则会返回false。
需要注意的是函数运行之后数组顺序会变化,如果存在下一个排序那数组会变为下一个排序,否则会变为正序,也就是第一个排序,所以如果不想改变数组顺序的话需要备份。举例来说,对于数组A={3,1,2},第一次运行next_permutaion(A,A+3)之后A= {3,2,1},第二次运行后就变为{1,2,3}。
对于这道题,我们只需要使用模板知识和next_permution函数,接着直接输出就可以了。
//OOP 下一个排列(函数模板)
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
template<typename T>
void getNext(T* t, int n) {
next_permutation(t, t + n);
for (int i = 0; i < n - 1; i++) {
cout << t[i] << " ";
}cout << t[n - 1] << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
char type;
int n;
cin >> type >> n;
if (type == 'C') {
char* p = new char[n];
for (int i = 0; i < n; i++) {
cin >> p[i];
}
getNext(p, n);
delete[] p;
}
else if (type == 'I') {
int* p = new int[n];
for (int i = 0; i < n; i++) {
cin >> p[i];
}
getNext(p, n);
delete[] p;
}
else if (type == 'D') {
double* p = new double[n];
for (int i = 0; i < n; i++) {
cin >> p[i];
}
getNext(p, n);
delete[] p;
}
else if (type == 'S') {
string* p = new string[n];
for (int i = 0; i < n; i++) {
cin >> p[i];
}
getNext(p, n);
delete[] p;
}
}
//system("pause");
return 0;
}