博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Old Sorting(转化成单调序列的最小次数,置换群思想)
阅读量:4656 次
发布时间:2019-06-09

本文共 2172 字,大约阅读时间需要 7 分钟。

 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
#include
#include
#include
#define mem(x, y) memset(x, y, sizeof(x))using namespace std;const int INF = 0x3f3f3f3f;const int MAXN = 10010;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 = 0, T; scanf("%d", &T); while(T--){ scanf("%d", &N); for(int i = 1; i <= N; i++){ scanf("%d", &dt[i].v); dt[i].pos = i; } sort(dt + 1, dt + N + 1); mem(vis, 0); int ans = 0; for(int i = 1; i <= N; i++){ if(!vis[i]){ int num = 0; int j = i; while(!vis[j]){ vis[j] = 1; num++; j = dt[j].pos; } ans += num - 1; } } printf("Case %d: %d\n", ++kase, ans); } return 0;}

 

转载于:https://www.cnblogs.com/handsomecui/p/5413999.html

你可能感兴趣的文章
浏览器-04 WebKit 渲染2
查看>>
异常处理
查看>>
页签切换
查看>>
基于MyBatis框架链接数据库
查看>>
扩展 Jianyi的SmartQuery,正式发布 ListQuery WebPart,已发布到Codeplex.CamlQuery项目中...
查看>>
jenkins配置邮箱服务器(126邮箱)
查看>>
Java中String类通过new创建与直接赋值的区别
查看>>
文件实时同步(rsync+inotify)
查看>>
AlertDialog
查看>>
《设计前的质量》阅读笔记1
查看>>
python闭包和延迟绑定
查看>>
C#设计模式系列 3 ----Strategy 策略模式 之--007大破密码危机
查看>>
访问树中的所有元素(DOM)
查看>>
(转)C#制作进度窗体
查看>>
博客园页面设置
查看>>
【Alpha】Daily Scrum Meeting第五次
查看>>
git 路径中文转换成编码的解决
查看>>
2.19
查看>>
win10安装mongodb-win32-x86_64-2008plus-ssl-3.4.10-signed
查看>>
sql 补齐字段位数
查看>>