首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【LightOJ】1166 - Old Sorting(置换群)

【LightOJ】1166 - Old Sorting(置换群)

作者头像
FishWang
发布2025-08-26 21:18:52
发布2025-08-26 21:18:52
2120
举报

点击打开题目

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

置换群的经典应用,求出每个群的元素个数,减一就是这个群交换的次数。最后求个和就行了。

代码如下:

代码语言:javascript
复制
#include <cstdio>
#include <cstring>
#define CLR(a) memset(a,0,sizeof(a)) 
int main()
{
	int n;
	int u;
	int num[111];
	bool used[111];
	int ans;
	scanf ("%d",&u);
	int Case = 1;
	while (u--)
	{
		scanf ("%d",&n);
		for (int i = 1 ; i <=  n ; i++)
			scanf ("%d",&num[i]);
		printf ("Case %d: ",Case++);
		ans = 0;
		CLR(used);
		for (int i = 1 ; i <= n ; i++)
		{
			if (!used[i])
			{
				int t = num[i];
				used[i] = true;
				int d = 1;
				while (t != i)
				{
					used[t] = true;
					t = num[t];
					d++;
				}
				ans += d - 1;
			}
		}
		printf ("%d\n",ans);
	}
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Input
  • Output
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档