描述
Given a permutation of numbers from 1 to n, we can always get the sequence 1, 2, 3, …, n by swapping pairs of numbers. For example, if the initial sequence is 2, 3, 5, 4, 1, we can sort them in the following way:
2 3 5 4 1
1 3 5 4 2
1 3 2 4 5
1 2 3 4 5
Here three swaps have been used. The problem is, given a specific permutation, how many swaps we needs to take at least.
输入
The first line contains a single integer t (1 <= t <= 20) that indicates the number of test cases. Then follow the t cases. Each case contains two lines. The first line contains the integer n (1 <= n <= 10000), and the second line gives the initial permutation.
输出
For each test case, the output will be only one integer, which is the least number of swaps needed to get the sequence 1, 2, 3, …, n from the initial permutation.
样例输入
2
3
1 2 3
5
2 3 5 4 1
样例输出
0
3
大意:
用最少的交换次数,把从1到n的n个数排序
思路:
因为是从1到n的n个数,从头开始循环,可以直接把值为n放到n位置上去,运气好的话,交换一次还可能排好两个数,这是贪心思想所在,不然跟选择排序没啥差别。
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int a[10005];
int k;
cin>>k;
while(k--)
{
int n;
cin>>n;
int sum=0;
for(int i=1; i<=n; i++)
cin>>a[i];
for(int i=1; i<n; i++)
{ if(a[i]==i)continue;
for(int j=i+1;j<=n;j++)
{
if(a[j]==i)
{swap(a[j],a[i]);
sum++;
break;}
}
}
cout<<sum<<endl;
}
return 0;
}