No.16 Sorting by Swapping

原文链接:https://acs.jxnu.edu.cn/contest/24/board/challenge/Cicon-default.png?t=M0H8https://acs.jxnu.edu.cn/contest/24/board/challenge/C

原文:

Sorting by Swapping

描述:

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.

输入:

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.

输出:

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.

样例输入:

2
3
1 2 3
5
2 3 5 4 1

样例输出:

0
3

参考译文:

交换排序

描述:

给定从1到n的n个数字的数列,我们需要得到的是这n个数字的升序排列,经过一系列的交换操作,操作如下:

2 3 5 4 1
1 3 5 4 2
1 3 2 4 5
1 2 3 4 5
上述为三步交换操作,现在你要解决的问题是,给定一个n个整数的任意序列,找到得到上述序列的最小操作数。

输入:

测试数据包含多组,第一行包含一个整数T,用于表示测试的组数。

每组测试包含两行,第一行为一个整数n,接下来一行为n个整数的序列,每两个数之间用一个空格间隔。

输出:

每组测试对应一行输出,输出包含一个整数,用来表示最小操作数。

样例输入:

2
3
1 2 3
5
2 3 5 4 1

样例输出:

0
3

参考代码:

#include<iostream>
using namespace std;
int main()
{
	int T;
	cin >> T;
	for(int t = 0;t < T;++t){
		int n;
		cin >> n;
		int number[n+10];
		for(int i = 1;i <= n;++i){
			cin >> number[i];
		}
		int cnt = 1;
		int swap = 0;
		int num = 0;
		while(cnt <= n){
			if(number[cnt] == cnt){
				++cnt;
			}
			else{
				swap = number[cnt];
				number[cnt] = number[swap];
				number[swap] = swap;
				++num;
			}
		}
		cout << num << endl;
	}
	return 0;
 }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

「已注销」

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

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

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

打赏作者

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

抵扣说明:

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

余额充值