using
System;
using
System.Collections.Generic;
using
System.Linq;
public
class
GFG
{
class
Pair
{
public
int
first, second;
public
Pair(
int
f,
int
s)
{
first = f;
second = s;
}
}
static
int
minSwapsToSort(
int
[] arr,
int
n)
{
List<Pair> arrPos =
new
List<Pair>();
for
(
int
i = 0; i < n; i++)
{
arrPos.Add(
new
Pair(arr[i], i));
}
arrPos.Sort((Pair A, Pair B) => {
return
A.first - B.first;
});
bool
[] vis =
new
bool
[n];
int
ans = 0;
for
(
int
i = 0; i < n; i++)
{
if
(vis[i] || arrPos[i].second == i)
continue
;
int
cycle_size = 0;
int
j = i;
while
(!vis[j])
{
vis[j] =
true
;
j = arrPos[j].second;
cycle_size++;
}
ans += (cycle_size - 1);
}
return
ans;
}
static
int
minSwapToMakeArraySame(
int
[] a,
int
[] b,
int
n)
{
Dictionary<
int
,
int
> mp =
new
Dictionary<
int
,
int
>();
for
(
int
i = 0; i < n; i++)
mp.Add(b[i], i);
for
(
int
i = 0; i < n; i++)
b[i] = mp[a[i]];
return
minSwapsToSort(b, n);
}
static
void
KswapPermutation(
int
[] arr,
int
n,
int
k)
{
int
[] a =
new
int
[n];
for
(
int
i = 0; i < n; i++)
a[i] = arr[i];
Array.Sort(arr);
for
(
int
idx = 0; idx < n / 2; idx++)
{
int
t = arr[idx];
arr[idx] = arr[n - idx - 1];
arr[n - idx - 1] = t;
}
do
{
int
[] a1 =
new
int
[n];
int
[] b1 =
new
int
[n];
for
(
int
i = 0; i < n; i++)
{
a1[i] = arr[i];
b1[i] = a[i];
}
if
(minSwapToMakeArraySame(a1, b1, n) <= k)
{
for
(
int
i = 0; i < n; i++)
Console.Write(arr[i] +
" "
);
break
;
}
}
while
(prev_permutation(arr, n));
}
static
bool
prev_permutation(
int
[] s,
int
n)
{
int
i = n - 1;
while
(i > 0 && s[i - 1] <= s[i])
{
if
(--i == 0)
{
return
false
;
}
}
int
j = i;
while
(j < n && s[j] <= s[i - 1])
{
j++;
}
j--;
int
t = s[i - 1];
s[i - 1] = s[j];
s[j] = t;
int
l = i;
int
r = n - 1;
while
(l < r)
{
t = s[l];
s[l] = s[r];
s[r] = t;
l++;
r--;
}
return
true
;
}
static
public
void
Main()
{
int
[] arr = { 2, 1, 3 };
int
n = arr.Length;
int
k = 1;
Console.WriteLine(
"Largest permutation after "
+ k
+
" swaps:"
);
KswapPermutation(arr, n, k);
}
}