题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805403651522560
注意效率问题。用一个变量保存不在本位的最小序号。而且数组要表示位置,不然要超时。
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 10;
int pos[maxn];
int main(){
int n, num = 0, m;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &m);
pos[m] = i;
if (i == m && i)
num++;
}
int time = 0;
int k = 1;
while(num < n - 1){
if(!pos[0]){
while(k < n){
if(k != pos[k]){
swap(pos[0], pos[k]);
time++;
break;
}
k++;
}
}
else{
while(pos[0]){
swap(pos[0], pos[pos[0]]);
time++;
num++;
}
}
}
printf("%d", time);
return 0;
}