Given any permutation of the numbers {0, 1, 2,…, N−1}, it is easy to sort them in increasing order. But what if Swap(0, *) is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:

Swap(0, 1) => {4, 1, 2, 0, 3}
Swap(0, 3) => {4, 1, 2, 3, 0}
Swap(0, 4) => {0, 1, 2, 3, 4}

Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.

Input Specification:

Each input file contains one test case, which gives a positive N (≤10^5) followed by a permutation sequence of {0, 1, …, N−1}. All the numbers in a line are separated by a space.

Output Specification:

For each case, simply print in a line the minimum number of swaps need to sort the given permutation.

Sample Input:

10
3 5 7 2 6 4 9 0 8 1

Sample Output:

9

思路

  • 如果在交换过程中出现数字0在0号位的情况,就随意选择一个还没有回到“本位”的数字,让其与数字0交换位置

注意点

  • 在循环中寻找一个不在本位上的数时,如果每次都从头开始遍历序列中的数,则会有两组数据超时(因为复杂度是二次方级别的)。合适的做法是从整体上定义一个变量 k,用来保存目前序列中不在本位上的最小数(初试为1),当交换过程中出现0回归本位的情况时,总是从当前的 k 开始继续增大寻找不在本位上的数,这样能保证复杂度从整体上是线性级别(k 从 1 增长到 n)
  • 该题用一个 index[] 数组表示下标值所在的位置即可,无需原始数组
#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn = 100000;

int main() {
    int n, index[maxn], num, k = 1, ans = 0, cnt = 0;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &num);
        index[num] = i;
        if (index[num] != num && num != 0) {
            cnt++;
        }
    }
    while (cnt != 0) {
        if (index[0] == 0) {
            for (; k < n; k++) {
                if (index[k] != k) {
                    break;
                }
            }
            swap(index[0], index[k]);
        } else {
            swap(index[0], index[index[0]]);
            cnt--;
        }
        ans++;
    }
    printf("%d", ans);
    return 0;
}