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
将各个数存入数组P[];
如果0在pos处(pos!=0),即P[pos]=0,就交换0和pos,如题目所给测试用例,第一步0和7交换,这样7就归位了,然后0到了pos=2处,再交换0和2;
如果在交换过程中,0到了pos=0怎么办呢?就让0和随便什么还没有归位的数交换,这样又可以继续执行之前描述的过程。Customized Test Case
Input
4 0 1 3 2
Output
3
#include <cstdio>
using namespace std;
#include <vector>
#include <algorithm>
#include <map>
const int MAX=100000+10;
int P[MAX];
map<int,int> M; //first:数字; second:在P数组中的下标
int main(){
int N;
scanf("%d",&N);
int pos0=-1;//0的位置
int count=0;//已经在正确位置上的数字。0不算
int num=0;//交换的次数
for(int i=0;i<N;i++) {
scanf("%d",&P[i]);
if(P[i]==i) {
if(P[i]!=0) count++;
}
else{
if(P[i]!=0) M[P[i]]=i;
}
if(P[i]==0) pos0=i;
}
int tmp;
while(count<N-1){
// printf("pos0=%d\n",pos0);
if(pos0!=0) {
count++;
num++;
tmp=M[pos0];
M.erase(pos0);
// printf("swap1 %d %d\n",P[pos0],P[tmp]);
swap(P[tmp],P[pos0]);
pos0=tmp;
}
else{
num++;
map<int,int>::iterator it=M.begin();
tmp=it->second;
// printf("%d %d\n",it->first,it->second);
M[it->first]=pos0;
// printf("swap2 %d %d\n",P[pos0],P[tmp]);
swap(P[pos0],P[tmp]);
pos0=tmp;
}
}
printf("%d",num);
return 0;
}