题意:
现有标号1到n的数,随机排列。可以进行两两交换,最后使这个数列升序排列。要求交换次数最少。
因为是朝着贪心那个方向去想有点先入为主的感觉,所以一开始用O(N)的方法贪错了,wa了。
思路:每个元素都需要回到的位置是确定,所以从左到右依次还原每个位置上的元素就好。
为什么这样是对的呢?
交换次数一定是小于等于n的,之所以会有小于的情况是因为如果两个元素刚好在最对方的位置上就只用交换1次。而两个元素交换了位置可能会对之后的一些交换产生影响,不能单纯的从一开始的状态就判断出结果。所以要一边模拟这个交换的过程一边计算。
附两组用于检查的数据:
Input -
2
10
3 4 5 6 10 9 8 1 2 7
10
5 9 3 4 6 7 1 8 10 2
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
int ans,n,t,a[105],flag,tot;
int main()
{
freopen("in.txt","r",stdin);
scanf("%d\n",&t);
tot=0;
while(t--)
{
tot++;
scanf("%d",&n);
ans=0;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=n;i++)
{
if(a[i]!=i)
{
ans++;
for(int j=i+1;j<=n;j++)
if(a[j]==i)
{
swap(a[i],a[j]);
break;
}
}
}
printf("Case %d: %d\n",tot,ans);
}
}