IDEA
1.注意输入的数字从0-n-1,意思是让数字存在其对应下标下
2.题目只让0和某数交换,交换次数尽量少,则尽量让该数放在正确位置下,完后就不参与交换了
3.考虑两种情况:array[0]==0,0本身在正确位置,若还有不在正确位置的数字,则0与其交换;
array[0]!=0,让通过交换使得array[0]到正确位置,指导位置0有正确数,即0.位置;然后重复第一种情况
IDEA
#include<iostream>
#include<fstream>
using namespace std;
int findpos(int* array,int begin,int end){
for(int i=begin;i<end;i++){
if(array[i]!=i){
return i;
}
}
return 0;
}
//void output(int *array,int n){
// for(int i=0;i<n;i++){
// cout<<array[i]<<" ";
// }
//}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
#endif
int n;
cin>>n;
int *array=new int[n];
for(int i=0;i<n;i++){
cin>>array[i];
}
int index=1;
index=findpos(array,index,n);
int count=0;
while(index){//index!=0,表示还有没有归为的数
if(array[0]==0){
//swap
array[0]=array[index];
array[index]=0;
// output(array,n);
// cout<<endl;
count++;
}
while(array[0]!=0){//不在正确位置上,那要通过变换使得v[0] == 0
int tmp=array[0];
array[0]=array[tmp];
array[tmp]=tmp;
// output(array,n);
// cout<<"-"<<endl;
count++;
}
index=findpos(array,index,n);//0在自己位置上,找到第一个不在正确位置上的数
}
cout<<count<<endl;
#ifndef ONLINE_JUDGE
fclose(stdin);
#endif
return 0;
}