Description
大家知道,给出正整数n,则1到n这n个数可以构成n!种排列,把这些排列按照从小到大的顺序(字典顺序)列出,如n=3时,列出1 2 3,1 3 2,2 1 3,2 3 1,3 1 2,3 2 1六个排列。
任务描述:
给出某个排列,求出这个排列的下k个排列,如果遇到最后一个排列,则下1排列为第1个排列,即排列1 2 3…n。
比如:n = 3,k=2 给出排列2 3 1,则它的下1个排列为3 1 2,下2个排列为3 2 1,因此答案为3 2 1。
Input
Output
Sample Input
3 3 1 2 3 1 3 1 3 2 1 10 2 1 2 3 4 5 6 7 8 9 10
Sample Output
3 1 2 1 2 3
1 2 3 4 5 6 7 9 8 10
解题过程:
最近ACM培训讲了枚举。其中讲了next_permutation(a,a+len)函数。返回值为bool类型,该函数可以自动生成下一个序列,并且若是字母按字典序排序,数字按从小到大排列。若序列已经是最大序列,则返回false,否则返回true;但是,即使是返回false,若答应该序列的下一个排列,输出为排列中最小的序列。
#include <iostream>
#include<cstdio>
#include<algorithm>
#define max 1025
using namespace std;
int main()
{
int m,n,k,a[max];
scanf("%d",&m);
while(m--)
{
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
for(int i=0;i<k;i++)
next_permutation(a,a+n);
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
return 0;
}