Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 13979 | Accepted: 5712 |
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
Source
這道題首先會想到<algorithm>中 按照字典序排列的函數 next_permutation() 在stl中定義如下:
bool next_permutation(_BidirectionalIterator __first,_BidirectionalIterator __last)
然而如果使用cin輸入 會導致超時.
所以使用scanf輸入 成功AC
#include<iostream>
#include<algorithm>
using namespace std;
#define N 1050
int main(){
int m;
scanf("%d",&m);
while(m--){
int n;
int k;
int nums[N];
scanf("%d %d",&n,&k);
for(int i=0; i<n; i++){
scanf("%d",&nums[i]);
}
for(int i=0; i<k; i++){
next_permutation(nums,nums+n);
}
for(int j=0; j<n; j++){
printf("%d ",nums[j]);
}
printf("\n");
}
}