乱序数组或字符最小交换次数

如果是要求为只能交换相邻的两个元素,使数组或者是字符串间有序;

思路:计算数组中或者是字符串间的中元素的逆序数.

如:2 1 3 4   此时逆序数为:1;最小交换次数就为1;

       3 2 1 4   此时逆序数为:3;最小交换次数就为3;

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <mutex>
#include <map>
#include <list>
#include <string>
#include <deque>
#include <queue>
#include <stack>
#include <vector>
#include <math.h>
#include <unordered_map>
#include <functional>
#include <algorithm>

using namespace std;
int main()
{
	int n = 0;

	cin >> n;
	string s;
	for (int i = 0; i < n; ++i) {
		char c;
		cin >> c;
		s += c;

	}

	//如果是只能交换相邻的两个元素,促使数组中的元素顺序保持有序
	int res = 0;
	for (int i = 0; i < s.length() - 1; ++i) {
		for (int j = i + 1; j < s.length(); ++j) {

			if (s[i] > s[j]) {
				res++;
			}
		}
	}
	cout << res;
	system("pause");
	return 0;
}

如果是交换两元素是不为相邻的两元素,是任意的两个元素.

思路: 检查数组中有多少个循环节,循环节可以这样理解,比如:5 4 3 2 1 这个递减的数组,此时可以将5和1进行互换,4和2进行互换,3自身和自身交换,然后两者就会到达自己所要排序的最终位置。此时循环节为3;最终的交换次数为 n - 循环节个数

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
	
	map<int, int> m;
	vector<int> nums;
	vector<bool> flags(10001, false);

	int n;
	cin >> n;

	nums.push_back(0);
	//排序的数组,整体是大于0;
	for (int i = 1; i <= n; ++i) {
		int num = 0;
		cin >> num;
		nums.push_back(num);
		m[nums[i]] = i;
	}

	sort(nums.begin(), nums.end());

	int res = 0;
	for (int i = 1; i <= n; ++i) {
		if (!flags[i]) {
			int index = i;

			while (!flags[index]) {
				flags[index] = 1;
				index = m[nums[index]];
			}
			res++;
		}
	}

	cout << n - res;
	system("pause");
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值