总结:
1.算法还是很好想,如果0不在0位,就将0与该在这个位置上的数交换,如果0在0位,就把它与任意一个不在正确位置上的数交换。写的时候要注意细节,我用了一个pos[i]来表示i在start数组的位置,交换过后不仅要交换数字,还要交换位置。用了一个cnt来确定什么时候停止循环,cnt--不再正确位置上的数的个数,当其等于0的时候停止循环
2.要注意如果一个数(下标为index)和0交换过了后再下一次0出现再0位置上时,这个Index就肯定处在正确位置上了,下一次找直接从index开始找
代码:
#include<iostream>
using namespace std;
int start[110000];
int pos[110000];
void swap1(int&a,int&b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int m;
int cnt = 0;
int total = 0; int index = 1;
scanf("%d",&m);
for (int i = 0; i < m; i++)
{
scanf("%d",&start[i]);
if (start[i] != 0 && start[i] != i)cnt++;
pos[start[i]] = i;
}
int sum = 0;
while (cnt>0)
{
if (pos[0] != 0)
{
total = pos[0]; //0的位置
swap1(start[total], start[pos[total]]); //pos[total]--total的位置
cnt--;swap1(pos[0],pos[total]); sum++;
}
else //0在0位
{
//交换start[0]和任意一个不在位置上的数
//从第一个元素开始看,如果不是正确位置,交换
while (start[index] == index)
{
index++;
}
swap1(start[0],start[index]);
pos[0] = index; pos[start[0]] = 0;
sum++;
}
}
printf("%d",sum);
return 0;
}