#include <bits/stdc++.h>
using
namespace
std;
bool
mycmp(pair<
int
,
int
> a,
pair<
int
,
int
> b)
{
return
a.first > b.first;
}
int
minSwapsAsc(vector<
int
> arr,
int
n)
{
pair<
int
,
int
> arrPos[n];
for
(
int
i = 0; i < n; i++) {
arrPos[i].first = arr[i];
arrPos[i].second = i;
}
sort(arrPos, arrPos + n);
vector<
bool
> vis(n,
false
);
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] = 1;
j = arrPos[j].second;
cycle_size++;
}
if
(cycle_size > 0) {
ans += (cycle_size - 1);
}
}
return
ans;
}
int
minSwapsDes(vector<
int
> arr,
int
n)
{
pair<
int
,
int
> arrPos[n];
for
(
int
i = 0; i < n; i++) {
arrPos[i].first = arr[i];
arrPos[i].second = i;
}
sort(arrPos, arrPos + n, mycmp);
vector<
bool
> vis(n,
false
);
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] = 1;
j = arrPos[j].second;
cycle_size++;
}
if
(cycle_size > 0) {
ans += (cycle_size - 1);
}
}
return
ans;
}
int
minimumSwaps(vector<
int
> arr)
{
int
S1 = minSwapsAsc(arr, arr.size());
int
S2 = minSwapsDes(arr, arr.size());
return
min(S1, S2);
}
int
main()
{
vector<
int
> arr{ 3, 4, 2, 5, 1 };
cout << minimumSwaps(arr);
return
0;
}