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到N-1的序列,你只能进行swap(0,*)操作,求最少交换次数使得此序列有序。
思路
分析后得出,有序后的序列的第i个数字是i(0<=i<=N-1)。而长度为N的序列最多经过N-1次交换可以成为有序。
所以我们得出如下算法:
- 如果当前0的下标为j(1<=j<=N-1),则将0与数字j交换,这一次交换就至少使得一个数字有序。
- 如果0下标为0,这时候只能将0与任意一个不在本位上的数字进行交换。
- 为了不需要每次都遍历数组判断是否有序,我们使用一个计数器left来记录除0外不在本位上数字的个数,当它为0时整个序列有序(因为除0外的数字都在本位上,那么0就一定在本位上了)。
- 为了实现以上功能,我们使用反向映射来存储数组,使用pos[t]来存储数字t所在的下标。交换两个元素等价于交换它们的下标。
代码
#include <cstdio>
#include <algorithm>
using namespace std;
#define MAX_N 100000
int main() {
int N, pos[MAX_N];
scanf("%d", &N);
int left = N - 1;
for(int i = 0, t; i < N; i++){
scanf("%d", &t);
pos[t] = i;
if(t != 0 && t == i) left--;
}
int res = 0;
int k = 1;
while (left > 0) {
if(pos[0] == 0){
while (pos[k] == k) {
k++;
}
swap(pos[0], pos[k]);
}else{
swap(pos[0], pos[pos[0]]);
left--;
}
res++;
}
printf("%d", res);
return 0;
}