poj 1833

排列
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

第一行是一個正整數m,表示測試數據的個數,下面是m組測試數據,每組測試數據第一行是2個正整數n( 1 <= n < 1024 )和k(1<=k<=64),第二行有n個正整數,是1,2 … n的一個排列。

Output

對於每組輸入數據,輸出一行,n個數,中間用空格隔開,表示輸入排列的下k個排列。

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



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章