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交换)
*/
#include <iostream>
using namespace std;
#include <vector>
int main(){
int n, num;
cin >> n;
vector<int> v(n); //存放当前数字 所处的位置编号
/*
第一步:找到除零以外不在本位上的个数
这一步的原因是因为,如果一个排列中有 不在本位的数,那么我们就必须用0去与之交换
如果没有,那就是一个完好的序列
自己思考的时候尚有欠缺,只想到了下面的循环该怎么做,却未考虑如何控制循环的次数
*/
int left = n - 1; //存放除0以外不在本位上的数的个数
for(int i=0; i<n; i++){
cin >> num;
v[num] = i;
if(num != 0 && num == i){ //除0以外 存在 在本位上的数
left--;
}
}
int count = 0; //交换次数
/*第二步就是 循环了*/
int k = 1; //从1开始枚举 找到 不在本位上的数 切记当一个数在本位是 则无需再动
while(left > 0){ //只要还有数 不在本位上
if(v[0] == 0){ //如果0在本位上 寻找一个当前不在本位上的数 与其交换
while(k < n){
if(v[k] != k){
swap(v[0], v[k]);
count++;
break; //因为找到一个 不在本位上的数 交换后 0 就不在本位上了 所以不适用 此if语句下的循环交换条件
}
k++;
}
}
while(v[0] != 0){ //如果0不在本位上,就将0所处的 位置编号 与 应当在这个位置编号的数 的位置编号 交换
swap(v[0], v[v[0]]);
count++;
left--; //每当一个数回到本位时,循环次数减一
}
}
cout << count << endl;
return 0;
}