71
技術社區[雲棲]
POJ1833 next_permutation函數應用
|
排列
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 |
題解:這題用STL中的next_permutation(pot1,opt2)函數能輕鬆解決
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int main()
{
int t,n,k,a[1100];
scanf("%d",&t);
while(t--)
{
cin>>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-1; i++)
printf("%d ",a[i]);
printf("%d\n",a[n-1]);
}
return 0;
}
最後更新:2017-04-02 15:15:01