ACM--Sorting by Swapping

Sorting by Swapping

Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:32768KB
Total submit users: 1514, Accepted users: 1381
Problem 10067 : No special judgement

Problem description

Given a permutation of numbers from 1 to n, we can always get the sequence 1, 2, 3, …, n by swapping pairs of numbers. For example, if the initial sequence is 2, 3, 5, 4, 1, we can sort them in the following way:

2 3 5 4 1
1 3 5 4 2
1 3 2 4 5
1 2 3 4 5

Here three swaps have been used. The problem is, given a specific permutation, how many swaps we needs to take at least.

Input

The first line contains a single integer t (1 <= t <= 20) that indicates the number of test cases. Then follow the t cases. Each case contains two lines. The first line contains the integer n (1 <= n <= 10000), and the second line gives the initial permutation.

Output

For each test case, the output will be only one integer, which is the least number of swaps needed to get the sequence 1, 2, 3, …, n from the initial permutation.

Sample Input

2
3
1 2 3
5
2 3 5 4 1

Sample Output

0
3

分析

要调换次数最好,那么尽量的每次调换的效率最高,因此先判断该数字是否应该在此位置,如果不在,将此数字调换到应该到的位置去,这样每一次交换都是有效交换(至少有一个数字到了自己应该到的位置)。
因此,这样的交换产生的交换次数最少,从而符合题意。

神奇的代码:

#include <iostream>
#include <algorithm>
using namespace std;
int a[10001]= {0};

int main() { 
int t;
	cin>>t;
	while(t--) {
		int sum=0;
		int n;
		cin>>n;
		for(int i=0; i<n; i++)
			cin>>a[i];
		for(int i=0; i<n; i++) {
			while(a[i]!=i+1) {//如果不应该在此位置
				swap(a[i],a[a[i]-1]);//将此数字调换到应该到的位置去,每一次交换都是有效交换,因此,这样的交换产生的交换次数最少,从而符合题意
				sum++;
			}
		}
		cout<<sum<<endl; 
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MORE_77

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值