一开始题目意思理解错误了
Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.
意思是寻找最少的交换次数
我理解成了最小需要交换的数字。
最后还是学了算法笔记算法
要点在于交换的时候0的位置和应该在0的位置上的数字交换
重点处理0再0号位置上但是排列没有完成的情况的讨论
需要交换0和下一个位置和数字不匹配的数字。
#include <cstdio>
#include <algorithm>
using namespace std;
void swap1(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int n,p[100010];
scanf("%d",&n);
int sum = n - 1;
int ans = 0;
for(int i = 0;i<n;i++)
{
int num;
scanf("%d",&num);
p[num] = i;
if(num == i && num != 0)
{
sum --;
}
}
int k = 1;
while(sum > 0)
{
if(p[0] == 0)
{
while(k<n)
{
if(p[k] != k)
{
swap1(&p[k],&p[0]);
ans++;
break;
}
k++;
}
}
while(p[0] != 0)
{
swap1(&p[0],&p[p[0]]);
ans++;
sum--;
}
}
printf("%d",ans);
return 0;
}