您的位置:首页 > 其它

POJ-1833 排列-字典序

2015-08-07 19:19 274 查看
排列

Time Limit: 1000MSMemory Limit: 30000K
Total Submissions: 17698Accepted: 7044
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

qinlu@POJ

#include <iostream>
#include <cstring>
#include <iomanip>
#include <stdio.h>
#include <cmath>
#include <algorithm>
using namespace std;

int main()
{
    int t,n,m,i;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        int a
;
        for(i=0; i<n; ++i)
            cin>>a[i];
        while(m--)
        {
            next_permutation(a,a+n);
        }
        for(i=0; i<n-1; ++i)
            cout<<a[i]<<" ";
        cout<<a[n-1]<<endl;
    }
    return 0;
}

//STL大法好,用next_permutation一下子就搞定了,这个函数是字典排序,调用几次就排序前几个
#include <iostream>
#include <cstring>
#include <iomanip>
#include <stdio.h>
#include <cmath>
#include <algorithm>
using namespace std;

int main()
{
    int t,n,m,i,a[1025];
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d", &n, &m);
        for(i=0; i<n; ++i)
            scanf("%d", &a[i]);
        while(m--)
        {
            next_permutation(a,a+n);
        }
        for(i=0; i<n-1; ++i)
            printf("%d ", a[i]);
        printf("%d", a[n-1]);
        printf("\n");
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: