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
以下是自己在pad上画的一个案例
以下是AC代码:
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdio>
#include<ctime>
#include<algorithm>
#include<iterator>
#include<vector>
#include<stack>
#include<set>
#include<queue>
#include<map>
#include<utility>
using namespace std;
const int N=1e5+2;
int n;
int pos[N]; //pos[i] 表示数字i 在序列中的位置
int main()
{
ios::sync_with_stdio(false);
while(cin>>n){
int num=0;//记录除了0以外不在本位上的数【手推一次即可看出】
int ans=0;
int x;
for(int i=0;i<n;i++){
cin>>x;
pos[x]=i;
if(pos[i]!=i){ //变成if(x!=0&&pos[i]!=i) 竟会有一个案例过不了??!!!
num++; //不在本位的数
}
}
//num--; //否则排好序后num仍然为1
int exchange=1;
while(num>0){
if(pos[0]==0){//如果0在0号位置上
//随意选择一个没有在本位的数进行交换,由于是随意,但是每次
//都用一个for循环来找第一个不在本位的数会超时,所以利用每个移回本位的数在后续
//操作中不再移动的特点,定义一个exchange来表示目前序列中不在本位上的最小数(初始化1)
while(exchange<n){
if(pos[exchange]!=exchange){
swap(pos[0],pos[exchange]); //将0与exchange 交换位置
ans++;
break;
}
exchange++;
}
}else{
while(pos[0]!=0){
swap(pos[0],pos[pos[0]]);
// swap(3,4) pos[0]=3 pos[3]=4
ans++;
num--;
}
}
}
cout<<ans<<endl;
}
system("pause");
return 0;
}