Next Permutation | ||||||
| ||||||
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 ≤ n, k ≤ 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");
}
}