Old Sorting(转化成单调序列的最小次数,置换群思想)

 Old Sorting

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 nintegers 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

题解:求转化成单调序列的最小次数;蓝桥杯那题一样。。。当初竟然没写出来。。。

有置换群的思想,对于每一个循环,只需要交换num - 1次就好了;把所有的加上就好了;

代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define mem(x, y) memset(x, y, sizeof(x))
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = ;
int vis[MAXN];
struct Node{
int pos,v;
friend bool operator < (Node a, Node b){
if(a.v != b.v){
return a.v < b.v;
}
else return a.pos < b.pos;
}
};
Node dt[MAXN];
int main(){
int N, kase = , T;
scanf("%d", &T);
while(T--){
scanf("%d", &N);
for(int i = ; i <= N; i++){
scanf("%d", &dt[i].v);
dt[i].pos = i;
}
sort(dt + , dt + N + );
mem(vis, );
int ans = ;
for(int i = ; i <= N; i++){
if(!vis[i]){
int num = ;
int j = i;
while(!vis[j]){
vis[j] = ;
num++;
j = dt[j].pos;
}
ans += num - ;
}
}
printf("Case %d: %d\n", ++kase, ans);
}
return ;
}
上一篇:备注ocp_ORACLE专题网络


下一篇:vue3.0子组件调用父组件的方法及computed、watch的使用