Time Limit: 2000MS | Memory Limit: 32768KB | 64bit IO Format: %lld & %llu |
Description
Given an array containing a permutation of 1 to n, you have to find the minimum number of swaps to sort the array in ascending order. A swap means, you can exchange any two elements of the array.
For example, let n = 4, and the array be 4 2 3 1, then you can sort it in ascending order in just 1 swaps (by swapping 4 and 1).
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case contains two lines, the first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers separated by spaces. You may assume that the array will always contain a permutation of 1 to n.
Output
For each case, print the case number and the minimum number of swaps required to sort the array in ascending order.
Sample Input
3
4
4 2 3 1
4
4 3 2 1
4
1 2 3 4
Sample Output
Case 1: 1
Case 2: 2
Case 3: 0
Source
每个最小置换群(n个元素)置换成最小字典序需要n-1次
思路:寻找每个最小置换群--
将此置换群分为若干个最小置换群--
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int zhuan[120];
int fafe[120];
int xu(int xx)
{
int lp=0;
int kp=zhuan[xx];
while (1)
{
lp++;
fafe[kp]=false;
if (kp==xx)
break;
kp=zhuan[kp];
}
return lp;
}
void s(int ca)
{
int n;scanf("%d",&n);
memset(fafe,true,sizeof(fafe));
for (int i=1;i<=n;i++)
scanf("%d",&zhuan[i]);
int s=0;
for (int i=1;i<=n;i++)
if (fafe[i])
s+=xu(i)-1;
printf("Case %d: %d\n",ca,s);
}
int main()
{
int t;scanf("%d",&t);
for (int i=1;i<=t;i++)
s(i);
return 0;
}