10-排序6 Sort with Swap(0, i) (25 分)
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
Note
- 精简版表排序,本质上是尽求移动次数最少,因此适合本题的swap
- 交换的次数求解
- 注意讨论a[0] = 0 , 若a[0] == 0 环的第二中情况就不存在了,因此交换的次数为 ni + 1 从1到k求和即等于所有多元环中元素的个数 + k,而其中多元环中元素的个数等于num - 单元环的个数 所以公式变为N - S + K
Code
#include<iostream>
using namespace std;
#define MAX 100100
int a[MAX];
int main() {
int i,num, S = 0, K = 0, flag = 0;
cin >> num;
for(i = 0; i < num; i++){
cin >> a[i];
if(a[i] == i) {
if(i == 0) flag = 1;
S++; //单元环个数
}
}
for(i = 0; i < num; i++){
if(a[i] != i){
K++; //多元环个数
while(a[i] != i){
int temp = a[i];
a[i] = i;
i = temp;
}
}
}
if(flag) cout << num - S + K;
else cout << num - S + K - 2;
}