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

解题思路

基本思路是,我们依次拿0与0所在位置代表的那个数(比如测试用例中0的位置为7)进行交换,最后得到有序序列

不过这样计算会出现一种特殊情况:就是0和0位置那个数发生了交换,那么算法到这里就终止了

遇到这种特殊情况,只需将0与最小的那个不在本位上的数交换就可以了。

也就是说

i != m[i]时,将0与数交换, i = m[i],继续遍历,代码如下:

#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
using namespace std;
const int MAXN = 100010;
int Numbers[MAXN];
int HashTable[MAXN];  //用来保存一个数所在的位置数
int main() {
	int N;
	scanf("%d", &N);
	for (int i = 0; i < N; ++i) {
		scanf("%d", &Numbers[i]);  //依次读入
		HashTable[Numbers[i]] = i;
	}
	int pos = HashTable[0];  //给出0的位置
	int counter = 0;
	//中断循环条件:当每个i == m[i]时
	while (true) {
		int tempPos = pos;
		int i;
		if (tempPos == 0) {
			//遍历寻找一个 i != m[i]的数字
			for (i = 1; i < N; ++i) {
				if (i != Numbers[i]) {
					swap(Numbers[tempPos], Numbers[i]);
					swap(HashTable[Numbers[tempPos]], HashTable[Numbers[i]]);
					counter++;
					pos = i;
					break;
				}
			}
			if (i == N) {
				break;   //数组已有序 退出循环即可
			}
		}
		else {
			pos = HashTable[pos];
			swap(Numbers[pos], Numbers[tempPos]);
			swap(HashTable[Numbers[pos]], HashTable[Numbers[tempPos]]);
			counter++;
		}
	}
	printf("%d", counter);
	system("PAUSE");
	return 0;
}