注:第二个for循环中,始终从0开始查找会使测试用例1、2超时,因此作一个小优化,即记住上次开始查找的位置start,下次从此处开始进行查找。
#include <stdio.h>
void swap(int *a, int *pos, int x, int y) {
int tmp = a[x];
a[x] = a[y];
pos[a[y]] = x;
a[y] = tmp;
pos[tmp] = y;
}
int main(int argc, char *argv[]) {
int n;
scanf("%d", &n);
int *a = new int[n];
int *pos = new int[n];
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
pos[a[i]] = i;
}
int count = 0;
bool flag = true;
int start = 0;
while (flag) {
while (pos[0] != 0) {
swap(a, pos, pos[0], pos[pos[0]]);
count++;
}
for (int i = start; i < n; i++) {
if (a[i] != i) {
swap(a, pos, 0, i);
start = i;
count++;
break;
} else if (i == n - 1) {
flag = false;
}
}
}
printf("%d\n", count);
return 0;
}