LightOJ - 1166 Old Sorting (置换群)

LightOJ - 1166
Time Limit: 2000MSMemory Limit: 32768KB64bit IO Format: %lld & %llu

Submit Status

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

Problem Setter: Jane Alam Jan
//题意:
给你n个数,和这n个数的序列,可以两两交换,问把它们变换为从小到大的序列,最少变换几次?
//思路:
就是一个简单的置换群,没啥说的
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define N 110
using namespace std;
struct zz
{
	int x;
	int id;
}p[N];
bool cmp(zz a,zz b)
{
	return a.x<b.x;
}
int a[N],vis[N];
int main()
{
	int t,T=1,n,i,j,k;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);		
		for(i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			p[i].x=a[i];
			p[i].id=i;
		}
		sort(p+1,p+n+1,cmp);
		int cnt,sum=0;
		memset(vis,0,sizeof(vis));
		for(i=1;i<=n;i++)
		{
			cnt=0;
			k=p[i].x;
			if(!vis[k])
			{				
				while(a[i]!=k)
				{
					vis[k]=1;vis[a[i]]=1;
					k=p[k].id;
					cnt++;
				}
				sum+=cnt;
			}			
		}
		printf("Case %d: %d\n",T++,sum);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值