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 (<=105) 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~N-1的任意排序,要求用0和另一个数交换的方法来排序该序列,要求最小的交换次数。
解题思路
1.一种思路是直接进行交换,计算总的交换次数。
- 当0不在0位置时,如果0在i位,则应该将0与数字i交换;
- 当0在0位置且数组还不是有序的时候,先将0与其后第一个不匹配的数字交换,然后再继续进行上一条的操作。
为了防止超时,应注意如下几点:
- 在接收输入的时候应创建两个数组,一个储存数值,另一个储存相应数值的索引;
- 在接收序列时,应记录除0外有多少个不匹配(不在相应位置)的数,该值将作为循环排序结束的判定值。因为每一次有效交换(即0不在0位)都将有一个数回到原位,当不匹配的数目为0时即代表排序完成;
- 当0处于0位时需要查找第一个不在对应位置的数,如果每次都从头遍历则会超时,此时应该记录下每次找到的位置,下一次继续从该处向后遍历,因为前面的所有数已经可以确定是”各居其位”了。
2.另一种思路是找出序列中的环,从而计算所需交换次数,而不需要实际的交换操作。
- 含0环,交换次数为环内非0元素的个数;
- 不含0环,交换次数为环内元素个数+1,因为此时0处于0位,需要将0交换到环内,形成一个含0环。
#include <cstdio>
using namespace std;
int a[100000];
int index[100000];
void swap(int x, int y) {
int t = a[x];
a[x] = a[y];
a[y] = t;
index[a[x]] = x;
index[a[y]] = y;
}
int main(void) {
int n; //数字个数
int t = 0; //需要进行交换的数的个数
int count = 0; //swap()交换次数
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int num;
scanf("%d", &num);
a[i] = num;
index[num] = i;
if (num != i && num != 0)
t++;
}
int k = 1; //第一个不匹配的数的索引
while (t > 0) {
if (a[0] == 0) {
for (int i = k; i < n; i++) {
if (i != a[i]) {
k = i + 1;
swap(0, i);
count++;
break;
}
}
}
swap(index[0], index[index[0]]);
t--;
count++;
}
printf("%d\n", count);
return 0;
}