lightoj 1166 - Old Sorting 【置换群】
2016-04-21 16:10
302 查看
题目链接:lightoj 1166 - Old Sorting
1166 - Old Sorting
PDF (English) Statistics Forum
Time Limit: 2 second(s) Memory Limit: 32 MB
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
Output for Sample Input
3
4
4 2 3 1
4
4 3 2 1
4
1 2 3 4
Case 1: 1
Case 2: 2
Case 3: 0
题意:给定n的一个排列,问你最少交换多少次才能使序列升序。
思路:一个元素个数为cnt的置换群最少需要cnt-1交换。
AC代码:
1166 - Old Sorting
PDF (English) Statistics Forum
Time Limit: 2 second(s) Memory Limit: 32 MB
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
Output for Sample Input
3
4
4 2 3 1
4
4 3 2 1
4
1 2 3 4
Case 1: 1
Case 2: 2
Case 3: 0
题意:给定n的一个排列,问你最少交换多少次才能使序列升序。
思路:一个元素个数为cnt的置换群最少需要cnt-1交换。
AC代码:
#include <cstdio> bool vis[110]; int a[110], pos[110]; int main() { int t, kcase = 1; scanf("%d", &t); while(t--) { int n; scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d", &a[i]); pos[a[i]] = i; vis[i] = false; } int ans = 0; for(int i = 1; i <= n; i++) { if(vis[a[i]]) continue; vis[a[i]] = true; int cnt = 1; int next = a[i]; while(pos[next] != a[i]) { next = pos[next]; cnt++; vis[next] = true; } //printf("%d\n", cnt); ans += cnt - 1; } printf("Case %d: %d\n", kcase++, ans); } return 0; }
相关文章推荐
- 最短路径分词
- Win7/8/10 删除多余IP
- c盘windows文件夹太大,installer文件夹太大
- SVM分类和训练
- SVM分类和训练
- position定位
- lightoj 1076 - Get the Containers 【二分 + 贪心】
- JQuery ==与=== 解说
- 05-树8 File Transfer
- HTML + CSS 之 闭合标签与双闭合标签
- 两位数与一位数相乘求和
- 任意十个数求和
- 赞助者名单
- 第一阶段站立会议3
- iOS 常用英语翻译
- APP更新名称
- jquery multiselect使用示例
- python 函数
- 剑指offer面试题 合并两个排序的链表
- lightoj 1016 - Brush (II) 【贪心】