思路:
找到一个不在位置上的数字,每次先通过0把一些数字归位,如果当前还没归位,就把9换到对应位置上。
代码:
#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
int pos[100005];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; ++i)
{
int num;
cin >> num;
pos[num] = i;
}
int ans = 0;
for (int i = 0; i < n; ++i)
{
if (pos[i] != i)
{
while (pos[0] != 0)
{
swap(pos[0], pos[pos[0]]);
ans++;
}
if (pos[i] != i)
{
swap(pos[0], pos[i]);
ans++;
}
}
}
cout << ans;
return 0;
}