https://practice.geeksforgeeks.org/problems/largest-permutation/0
Given a permutation of first n natural numbers as an array and an integer k. Print the lexicographically largest permutation after at most k swaps.

Input:
The first line of input contains an integer T denoting the number of test cases. Each test case contains two integers n and k where n denotes the number of elements in the array a[]. Next line contains space separated n elements in the array a[].

Output:
Print space separated n integers which form the largest permutation after at most k swaps.

Constraints:
1<=T<=100
1<=n<=1000
1<=a[i]<=1000
1<=k<=100 0

Example:
Input:
2
5 3
4 5 2 1 3
3 1
2 1 3
Output:
5 4 3 2 1
3 1 2

每次交换选择最大的到最前面。一次交换后可能影响后面的交换。
将数组从大到小排序 记录为 b[ ],与原数组对比,相同则不需交换。否则 对应的a[ i ] , b[ i ]交换。另需一个数组记录下标。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define sf(n) scanf("%d",&n)
#define pf(n) printf("%d",n)
#define pfc(c) printf(c)
#define fi(i,s,t) for(int i=s;i<t;i++)
#define fd(s,t) for(int i=s-1;i>=t;i--)
#define mem(a,c) memset(a,c,sizeof(a))
const int MAX=1000+10;
int t,n,a[MAX],k,b[MAX],c[MAX],tmp;
int cmp(int x,int y){
return x>y;
}
int main(){
freopen("in","r",stdin);
sf(t);
while(t--){
sf(n);sf(k);
fi(i,0,n) {
sf(a[i]);
b[i] = a[i];
c[a[i]] =i;
}
sort(b,b+n,cmp);
fi(i,0,n){
if(a[i] != b[i]){
tmp=a[i];
a[c[b[i]]] = a[i];
a[i] = b[i];
swap(c[tmp],c[b[i]]);
k--;
if(k<=0) break;
}
}
fi(i,0,n){
pf(a[i]);pfc(" ");
}
pfc("\n");
}
return 0;
}