Input Specification:
Each input file contains one test case, which gives a positive N (≤105) followed by a permutation sequence of {0, 1, ..., N−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
代码如下:
#include<iostream>
using namespace std;
int a[100010];//数字i所在的位置
int main()
{
int n,t,count=0;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>t;
a[t]=i;//数字t在第i个位置上
}
for(int i=0;i<n;i++)
{
if(a[i]!=i)
{
while(a[0]!=0)
{
swap(a[0],a[a[0]]);
count++;
}
if(a[i]!=i){
swap(a[0],a[i]);
count++;
}
}
}
cout<<count<<endl;
return 0;
}