题目描述
输入一个序列,输出其下一个字典序的排列
如:输入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个数据(用空格分隔)
输出
对每个测试数据输出其下一个字典序排列
------------------------------------------------------
输入样例:
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
AC代码:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
template <typename T>
void nextLexicographicalPermutation(T *sequence, int size)
{
if (next_permutation(sequence, sequence + size))
{
for (int i = 0; i < size; ++i)
{
if (i == size - 1)
{
cout << sequence[i];
}
else
cout << sequence[i] << " ";
}
cout << endl;
}
else
{
sort(sequence, sequence + size);
for (int i = 0; i < size; ++i)
{
if (i == size - 1)
{
cout << sequence[i];
}
else
cout << sequence[i] << " ";
}
cout << endl;
}
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; ++i)
{
char type;
cin >> type;
if (type == 'C')
{
int k;
cin >> k;
char *sequence = new char[k];
for (int j = 0; j < k; ++j)
{
cin >> sequence[j];
}
nextLexicographicalPermutation(sequence, k);
delete[] sequence;
}
else if (type == 'I')
{
int k;
cin >> k;
int *sequence = new int[k];
for (int j = 0; j < k; ++j)
{
cin >> sequence[j];
}
nextLexicographicalPermutation(sequence, k);
delete[] sequence;
}
else if (type == 'D')
{
int k;
cin >> k;
double *sequence = new double[k];
for (int j = 0; j < k; ++j)
{
cin >> sequence[j];
}
nextLexicographicalPermutation(sequence, k);
delete[] sequence;
}
else if (type == 'S')
{
int k;
cin >> k;
string *sequence = new string[k];
for (int j = 0; j < k; ++j)
{
cin >> sequence[j];
}
nextLexicographicalPermutation(sequence, k);
delete[] sequence;
}
}
return 0;
}