1. 程式人生 > 實用技巧 >10-排序6 Sort with Swap(0, i) (25point(s))

10-排序6 Sort with Swap(0, i) (25point(s))

10-排序6 Sort with Swap(0, i) (25point(s))

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

N 個數字的排列由若干個獨立的環構成。每一次都是和 0 做 swap,如果這個環裡面有 0,長度是 count,那麼每次都找和 0 值這個元素的下標相同的元素,做一次 swap。對於這個環本來就有 0,只需要做 count - 1 次 swap。若這個環裡面沒有 0,就要把 0 先 swap 進去,然後再歸位所以比環裡有 0 的多 2 次,需要 count + 1

次 swap。如果 count == 0 那這個元素不用和誰做 swap。

#include <stdio.h>

#define N 100000
/* 每次都和 0 做 swap,一次歸位一個數字 */
int main(int argc, char const *argv[])
{
    int a[N];
    int visited[N] = {0};
    int n, i;

    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    int sum = 0;      /* 總共需要多少次 swap */
    for (i = 0; i < n; i++) {
        if (!visited[i]) {
            visited[i] = 1;
            int index = i;
            int count = 0;  /* 環的元素個數,0 個不用做 swap */
            int next;
            while (a[index] != index) {
                visited[index] = 1;
                count++;
                next = a[index];
                a[index] = index;
                index = next;
            }
            if (count != 0) {
                sum = index == 0 ? sum + count - 1 : sum + count + 1;
            }
            // printf("index = %d, count = %d\n", index, count);
        }
    }
    printf("%d\n", sum);
    return 0;
}