poj 1833 排列

来源:互联网 发布:魔法王座升阶数据图 编辑:程序博客网 时间:2024/05/20 23:39


排列
Time Limit: 1000MS Memory Limit: 30000KTotal Submissions: 18585 Accepted: 7304

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

33 12 3 13 13 2 110 21 2 3 4 5 6 7 8 9 10

Sample Output

3 1 21 2 31 2 3 4 5 6 7 9 8 10

Source

qinlu@POJ


#include<cstdio>#include<string>#include<cstring>#include<iostream>#include<cmath>#include<algorithm>#include<vector>#include<iomanip>using namespace std;#define all(x) (x).begin(), (x).end()#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)typedef long long ll;typedef pair<int, int> pii;const int INF =0x3f3f3f3f;const int maxn= 1024 ;int a[maxn+10];int n,k;/*必须用c++交,g++会超时*/void print(){    for0(i,n)    {        if(i)  putchar(' ');        printf("%d",a[i]);    }    putchar('\n');}int main(){    int T;    scanf("%d",&T);    while(T--)    {        scanf("%d%d",&n,&k);//n个数,下k个        for0(i,n) scanf("%d",&a[i]);        while(k)        {           if(next_permutation(a,a+n)) ;//next_permutation 平均复杂度O(n)           else  sort(a,a+n);           k--;        }        print();    }   return 0;}


0 0