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;
}