方法:贪心策略:第一步,将0交换至位置0;第二步,若还有位置不等于该位置的值时,则先将它与0交换,再执行第一步。
pos数组存储的是该数所在的位置,与常规倒置,即pos[i]表示数值i所在的位置。
#include <iostream>
int pos[100010],N;
int main(){
scanf("%d",&N);
int temp,counts=0;
for(int i=0;i<N;i++){
scanf("%d",&temp);
pos[temp]=i;
}
while(pos[0]!=0){ //先将0交换至首位
temp=pos[0];
pos[0]=pos[temp];
pos[temp]=temp;
counts++;
}
for(int i=1;i<N;i++){
if(pos[i]!=i){
pos[0]=pos[i]; //先将pos[i]与pos[0]交换
pos[i]=0;
counts++;
while(pos[0]!=0){ //重复之前的操作,直到将0交换至首位
temp=pos[0];
pos[0]=pos[temp];
pos[temp]=temp;
counts++;
}
}
}
printf("%d",counts);
return 0;
}