Given any permutation of the numbers {0, 1, 2,..., N-1N?1}, it is easy to sort them in increasing order. But what if Swap(0, *) is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:
Swap(0, 1) => {4, 1, 2, 0, 3}
Swap(0, 3) => {4, 1, 2, 3, 0}
Swap(0, 4) => {0, 1, 2, 3, 4}
Now you are asked to find the minimum number of swaps need to sort the given permutation of the first NN nonnegative integers.
Input Specification:
Each input file contains one test case, which gives a positive NN (\le 10^5≤10?5??) followed by a permutation sequence of {0, 1, ..., N-1N?1}. All the numbers in a line are separated by a space.
Output Specification:
For each case, simply print in a line the minimum number of swaps need to sort the given permutation.
Sample Input:
10
3 5 7 2 6 4 9 0 8 1
Sample Output:
9
/*
评测结果
时间 结果 得分 题目 编译器 用时(ms) 内存(MB) 用户
2017-07-07 11:35 答案正确 25 5-16 g++ 24 2
测试点结果
测试点 结果 得分/满分 用时(ms) 内存(MB)
测试点1 答案正确 15/15 2 1
测试点2 答案正确 3/3 24 2
测试点3 答案正确 3/3 12 1
测试点4 答案正确 2/2 2 1
测试点5 答案正确 1/1 2 1
测试点6 答案正确 1/1 2 1
有点技巧性的题目,mooc上讲了,主要是找排序的环。有0环的交换次数为n-1,无零环为n+1
建了三个数组,A是存数,B是存i号元素放在了哪个位置,Checked是放这个元素有没有被访问过。
坑:必须加一个全局变量做搜索函数起点的备忘录用,否则搜索函数反复调用会导致超时
*/
#include<stdio.h>
#define MAXN 100000
int A[MAXN],B[MAXN],Checked[MAXN];
int gFindBeginPosition=0;
int FindUnchecked(int N)
{
int i;
for(i=gFindBeginPosition;i<N;i++)
{
if(!Checked[i])
return gFindBeginPosition=i;
}
return -1;
}
int main()
{
int i,N,p,sum;
int ringCount=0;
int nCount=0;
int zeroInPosition=0;
scanf("%d",&N);
for(i=0;i<N;i++)
{
scanf("%d",&A[i]);
B[A[i]]=i;
}
if(A[0]==0)
zeroInPosition=0;
else
zeroInPosition=-2;
while((p=FindUnchecked(N))+1)
{
Checked[p]=1;
if(A[p]!=p)
nCount++;
else continue;
while(!Checked[B[p]])
{
p=B[p];
Checked[p]=1;
nCount++;
}
ringCount++;
}
sum=nCount+ringCount+zeroInPosition;
printf("%d",sum);
}