哈理工oj 1372 Next Permutation【STL真好用系列】

本文探讨了如何在给定的排列中找到下一个更高的排列,适用于计算机科学领域内的排序算法研究。

Next Permutation
Time Limit: 1000 MSMemory Limit: 65536 K
Total Submit: 98(49 users)Total Accepted: 60(46 users)Rating: Special Judge: No
Description

A permutation is each one of the (n!) possible arrangements the elements in a set can take (where n is the number of elements in the set). Different permutations can be ordered according on how they compare lexicographically to each other; the first such-sorted possible permutation (the one that would compare lexicographically smaller to all other permutations) is the one which has all its elements sorted in ascending order, and the largest has all its elements sorted in descending order.

You need to determine the next k-th higher permutation of a given permutation of the set {1, 2, 3 … n}.

Input

There are multiple test cases. The first line of input is an integer T indicating the number of test cases. Then T test cases follow.

For each test case:

Line 1. This line contains two space-separated integers n and k (1 ≤ nk ≤ 1000)

Line 2. This line contains n space-separated integers indicating a permutation of {1, 2, 3 …n}

Output

For each test case:

Line 1. Output the next k-th higher permutation of the set {1, 2, 3 … n}.Separate the numbers by a single space.

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

Hint

In the first sample, all the permutations of {1, 2, 3} in lexicographical order are as below:

{1, 2, 3}

{1, 3, 2}

{2, 1, 3}

{2, 3, 1}

{3, 1, 2}

{3, 2, 1}

So the next first permutation of {2, 3, 1} is {3, 1, 2}.

Source
哈理工2012春季校赛 - 网络预选赛
Author
齐达拉图@HRBUST


如果有兴趣的小伙伴可以去做做hdu 1027 这两个题是一样的,只不过这个的输入稍微复杂些,直接套用库函数就行了~:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[10000];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,m;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        for(int i=1;i<=m;i++)
        {
            next_permutation(a+1,a+n+1);
        }
        printf("%d",a[1]);
        for(int i=2;i<=n;i++)
        {
            printf(" %d",a[i]);
        }
        printf("\n");
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值