原题:1067. Sort with Swap(0,*) (25)
解题思路:
每次把0所在位置上数找到是使用次数最少的。
然后按题目意思去模拟就好,不过会出现还未排序完0就在位置0上的情况,所以要加一个计数器来计算剩下的不在位置上的数,
当0回到0位置时,如果未排好,就找一个不在位置上的数与0交换(不要总是从头找,会超时,设置一个每次都更新的标记,每次都从标记往后找),再继续排序即可。
代码如下:
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 5;
int pos[maxn];
int main()
{
int n;
while(scanf("%d", &n) == 1)
{
for(int i = 0; i < n; i++)
{
int cnt;
scanf("%d", &cnt);
pos[cnt] = i;
}
int ans = 0;
int c = 0;
for(int i = 1; i < n; i++) if(pos[i] != i) c++;//统计不在位置上的非0数的个数
int k = 1;
while(c > 0)
{
if(pos[0] == 0)
{
while(pos[k] == k) k++;
swap(pos[0], pos[k]);
ans++;
}
while(pos[0] != 0)
{
swap(pos[0], pos[pos[0]]);
ans++;
c--;
}
}
printf("%d\n", ans);
}
return 0;
}