题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1067
解题思路:注意到0随时可能换到0位置,每次循环(循环条件为是否有未调整)先将0统一换到非0位置
代码如下:
#include <cstdio>
#include <vector>
using namespace std;
vector<int> s;
int main()
{
//freopen("C:\\Users\\Devon\\Desktop\\input.txt","r",stdin);
s.clear();
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
int temp;
scanf("%d",&temp);
s.push_back(temp);
}
int ret=0;
int i=0;
while(i<n){//每次循环保证前面的都是调整好的
if(s[i]!=i){
if(i!=0){//保证0位置不是0
int temp=s[0];
s[0]=s[i];
s[i]=temp;
ret++;
}
int temp1=0;//保证每次循环结束0位置为0
int temp2=s[temp1];
s[0]=0;
while(s[temp2]!=temp2){
temp1=s[temp2];
s[temp2]=temp2;
temp2=temp1;
ret++;
}
}
i++;
}
printf("%d\n",ret);
return 0;
}